一个简单例子的设计模式分析

在看《设计模式》一书的Factory Method方法中有下面的例子:
class Creator
{
  pulic:
    virtual Product* Create(ProductId);
};

Product* Creator::Create(ProductId id)
{
  if( id == MINE )
    return new MyProduct;
  if( id == YOURS )
    return new YourProduct;
  // repeat for remaining products...
  return 0;
}

class MyCreator : public Creator
{
  pulic:
    virtual Product* Create(ProductId);
};


Product* MyCreator::Creat(ProductId id)
{
  if( id == YOURS )
    return new MyProduct;
  if( id == MINE )
    return new YourProduct;
  // N.B.:Switched YOURS and MINE

  if( id == THEIRS )
    return new TheirProduct;
  return Creator::Create(id); //called if all others fail
}

这两个例子为Factory Method中创建实例的方法例子,仔细分析,我们将会
看到,这里面有几个if语句,非常类似策略的方式,不同的参数具有不同的
工作方法(new不同的对象),对比Creator与MyCreator中的Create中的函
数,发现在子类MyCreator中通过调用Creator中的Create方法,而在另外
情况下,则是由子类自己实现,因此这两个类之间又具有Decorator设计模式。
也就是说,尽管这是一个非常简单的例子,但已经涉及了三种设计模式:
   工厂方法(Factory Method)、策略模式(Strategy)和装饰模式(Decorator)
从中我们也可以明显看到,各类模式是相互间穿插在一起的,相互作用,形成一个整体。



ubunoon
blog:http://ubunoon.cnblogs.com

/*
*
* Copyright (c) 2011 Ubunoon.
* All rights reserved.
*
* email: netubu#gmail.com replace '#' to '@'
* http://www.cnblogs.com/ubunoon
* 欢迎来邮件定制各类验证码识别,条码识别,图像处理等软件
* 推荐不错的珍珠饰品,欢迎订购 * 宜臣珍珠(淡水好珍珠) */
原文地址:https://www.cnblogs.com/ubunoon/p/DesignPatternCreateSimpleAnalysis.html