简单工厂太简单了,其它并不是GOF提到的23种模式里面的。只是都喜欢这么叫,哈哈。
前言
之前看到GOF的《设计模式 可复用面向对象软件的基础》 ,看的时候觉得思想不错,但一直没有手支练下,今天回想起来,好像写的很多东西都可以在里面找到其思想。所以就重温下,顺便记下笔记。书上的例子都是c写的,由于现在工作中主要写Java代码较多,就用Java记录下。
简单工厂模式 Simple Factory
我先申明一下:
每种设计模式都有它的使用场景,我不会在这里去解释,只把原文贴出来,一是本人语言水平差,那些定理类的话很难通俗说出来,二是建议不要被这种定理蒙蔽思想,你去学习设计模式是写代码实战的,不是去考证书的。这种程度的代码,自己敲一次去运行分析一下,就什么都懂了。
另外,做完了之后记得去看下UML类图,网上一大把,我这里也不重画了,当然你自己做的时候就可以在纸上画。
问题:
If an application is to be portable, it needs to encapsulate platform dependencies. These “platforms” might include: windowing system, operating system, database, etc. Too often, this encapsulatation is not engineered in advance, and lots of #ifdef case statements with options for all currently supported platforms begin to procreate like rabbits throughout the code.
意图:
- Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
- A hierarchy that encapsulates: many possible “platforms”, and the construction of a suite of “products”.
- The new operator considered harmful.