zoukankan      html  css  js  c++  java
  • Prototype原型模式

    Prototype原型模式。

    用原型实例指定创建对象的种类。而且通过拷贝这些原型创建新的对象。

           原型模式就是用一个对象来创建还有一个同样的对象而无需知道创建的详细细节。并且大大提高了创建的效率。长处主要是这两个:
    1. 屏蔽创建的详细细节,如參数等。

    2. 创建的效率高。

      由于不必调用构造函数等。

           原型模式也是一种创建型模式。跟建造者模式,工厂模式系类一样,不同的是,建造者模式側重于一步一步建造对象。工厂模式側重于多个类的依赖。同样的是都是通过一个类(对象实例)来专门负责对象的创建工作。


         使用原型模式要先了解下拷贝构造函数的深拷贝和浅拷贝。

    代码:
    //Prototype.h
    #include "stdafx.h"
    #include<iostream>
    #include<cstring>
    using namespace std;
    class Prototype
    {
    public:
    	virtual ~Prototype()
    	{
    		cout << "~Prototype" << endl;
    	}
    	virtual Prototype* clone()const = 0;
    	virtual void show()const = 0;
    };
    
    class ConcreteProtype1 :public Prototype
    {
    public:
    	ConcreteProtype1(int len,char*str)
    	{
    		_length = len;
    		_str = new char[_length];
    		strcpy_s(_str, _length, str);
    	}
    	~ConcreteProtype1()
    	{
    		delete(_str);
    		cout << "~ConcreteProtype" << endl;
    	}
    
    	ConcreteProtype1(const ConcreteProtype1& rhs)
    	{
    		//实现深拷贝
    		_length = rhs._length;
    		_str = new char[_length];
    		if (_str != NULL)
    			strcpy_s(_str, _length, rhs._str);
    		cout << "copy construct ConcreteProtype1" << endl;
    	}
    	virtual Prototype* clone()const
    	{
    		return new ConcreteProtype1(*this);
    	}
    
    	virtual void show()const
    	{
    		cout <<"value:"<< _str << endl;
    		cout << "Address:" << &_str << endl;
    	}
    private:
    	int _length;
    	char* _str;
    };
    
    
    // PrototypePattern.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #include "Prototype.h"
    
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    
    	Prototype* p1 = new ConcreteProtype1(6,"hello");
    	Prototype *p2 = p1->clone();
    	p1->show();
    	p2->show();
    	getchar();
    	return 0;
    }
    



  • 相关阅读:
    JSP引擎的工作原理
    Hibernate缓存配置
    理解LinkedHashMap
    如何在CMD下运用管理员权限
    sun.misc.BASE64Encoder找不到jar包的解决方法
    访问WEB-INF目录中的JSP文件
    Servlet Filter(过滤器)、Filter是如何实现拦截的、Filter开发入门
    message from server: "Host 'xxx' is not allowed to connect to this MySQL server的解决
    深入Java单例模式
    (八)路径(面包屑导航)分页标签和徽章组件
  • 原文地址:https://www.cnblogs.com/slgkaifa/p/6922927.html
Copyright © 2011-2022 走看看