设计模式-----创建新

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值