- Program to an interface, not an implement.
- Satisfy the open-closed principle.
- Partition different tasks and assign them to different objects. It satisfy the single responsibility principle.
- you need to construct different children classes of a class using a parameter. At this time a factory method is quite easy for it. And pledge open-close principle.
- when calling the constructor by users could be harmful
- in an open-source library. When you want users not to use your constructor, but users must build some classes.
- Assign each class a single task: partition different tasks and assign them to different objects. When a class has multiple tasks, we need to create a family of classes instead of the single class.
6. What is the main idea of parameterized factory method? What is the advantages of parameterized factory method compared with factory pattern and simple factory pattern?
- it can be seen as a combination of simple factory and factory method. It is still a factory method, but a method can be parameterised to create different objects with different behaviors.
- Advantage: avoid large numbers of classes.
7. Please state the main idea of abstract factory. What is its advantage compared with factory method?
- Abstract factory method use abstract factory and the derived factories to build a family of related objects. It provide an interface for creating families of related or dependent objects without specifying the objects' concrete classes.
- The advantage is that there is no need to specifying concrete classes, it is more abstract and convenient as it can create a family of objects one time.
9. What is the key difference among simple factory, factory method, parameterized factory method, and abstract factory?
- Simple factory:扩展起来很困难,不符合开闭原则
- Factory method: 容易扩展,不过每次增加的类比较多,会导致类的数量急剧增加,代码冗长。
- Parameterized factory method: simple factory + factory method, 将一开始设计时已有的类用simple factory 的方法编写,新增的类用factory method的方法增加到后面去。
- Abstract factory:可以用来创建一系列相关的对象:比如windows的滚动条,按钮,鼠标指针;linux的滚动条,按钮,鼠标指针。
- It is used to listen to one subject simultaneously. When the subject changes its status, it will notify all the observers.
WeChat subscriptions
- When an abstraction has two aspects, one dependent on the other.
- When a change to one object requires changing others, and you don’t know how many objects need to be changed.
- When we are implementing a graphic user interface, every frame we should update all our graphics. In this case, observer design pattern can be used to notice every graphic instance to update its graphics.