生成器
封装一个对象的构造过程,并允许按步骤构造
参考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
}
};