Factory Method 模式

客户端使用代码如下
Creator c1 = new BulbCreator();
Creator c2 = new TubeCreator();
Light l1 = c1.factory();
Light l2 = c2.factory();
l1.TurnOn();
l1.TurnOff();
Console.WriteLine("-----------------");
l2.TurnOn();
l2.TurnOff();
Prototype模式
客户端使用代码如下
Prototype *obj1 = new ConcretePrototype1() ;//原型对象1
Prototype *obj2 = new ConcretePrototype2() ;//原型对象2
Prototype *newobj1 = obj1->Clone() ;//克隆对象1
Prototype *newobj2 = obj2->Clone() ;//克隆对象2
优点:复制自身。客户不知道需要对象的实际类型,只需知道它的抽象基类即可。(即有继承树的情况)
缺点:必须先有一个对象实例(即原型)才能clone。
Singleton模式
设计代码如下
public class Singleton{
private static Singleton instance = null;
public static Singleton getInstance() {
if (instance==null)
instance=new Singleton();
return instance;
}
}
需要注意的问题是 以上Singleton模式 不是线程安全的应该在 getInstance 中加上lock()模块
builder 模式
客户端使用代码如下
Director director = new Director( );
Builder b1 = new ConcreteBuilder1();
Builder b2 = new ConcreteBuilder2();
// Construct two products
director.Construct( b1 );
Product p1 = b1.GetResult();
p1.Show();
director.Construct( b2 );
Product p2 = b2.GetResult();
p2.Show();
product 是复杂的对象 b1 和 b2 分别构建 product不同的地方 产生出不同的 product