生成器、原型模式——创建型设计模式

生成器

封装一个对象的构造过程,并允许按步骤构造

参考JDK 1.8 源码简易的 StringBuilder 实现:

class AbstractStringBuilder 
{ 
protected:
	char[] value; 
	int count; 
public:
	AbstractStringBuilder(int capacity) 
	{ 
		count = 0; 
		value = new char[capacity];
	}
	AbstractStringBuilder append(char c) 
	{ 
		ensureCapacityInternal(count + 1); 
		value[count++] = c; 
		return this; 
	}
private:
	void ensureCapacityInternal(int minimumCapacity) 
	{ 
		if (minimumCapacity - value.length > 0) 
			expandCapacity(minimumCapacity); 
	}
	void expandCapacity(int minimumCapacity) 
	{ 
		int newCapacity = value.length * 2 + 2; 
		if (newCapacity - minimumCapacity < 0) 
			newCapacity = minimumCapacity; 
		if (newCapacity < 0) 
		{ 
			if (minimumCapacity < 0) 
				throw new OutOfMemoryError(); 
			newCapacity = Integer.MAX_VALUE; 
		}
		value = Arrays.copyOf(value, newCapacity); 
	} 
};

class StringBuilder:AbstractStringBuilder 
{ 
public: 
	StringBuilder() 
	{ super(16); }
	String toString() 
	{ 
		return new String(value, 0, count); 
	} 
};
class Client 
{ public:
	static void main(String[] args) 
	{ 
		StringBuilder sb = new StringBuilder(); 
		final int count = 26; 
		for (int i = 0; i < count; i++) 
		{ sb.append((char) ('a' + i)); }
		cout<<sb.toString(); //abcdefghijklmnopqrstuvwxyz
	}	 
};
原型模式

使用原型实例指定要创建对象的类型,通过复制这个原型来创建新对象

class Prototype 
{ 
	virtual Prototype myClone(); 
};
class ConcretePrototype:Prototype 
{ 
private: 
	String filed; 
public:
	ConcretePrototype(String filed) 
	{ this.filed = filed; }
	Prototype myClone() 
	{ return new ConcretePrototype(filed); }
	String toString() 
	{return filed; } 
};
class Client 
{ 
public: 
	static void main(String[] args) 
	{ 
		Prototype prototype = new ConcretePrototype("abc"); 
		Prototype clone = prototype.myClone(); 										cout<<clone.toString(); //abc
		} 
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值