对于编程思想的要求越来越高,今天有幸看到一篇不错的文章。在这里就把今天我读到的 和自己的一些想法 呈现给大家。
什么是设计模式呢? 模式就是套路。就好比做饭一样,我们按照菜单去炒作,切什么 剁什么,炒多久,饭菜就好了。而且如果我们严格按照菜谱来走的话 口味一般都会很鲜美,不会出什么纰漏。那设计模式也一下它教导我们在什么情况下 怎么的去设计一个东西 是比较合理的一种方法和套路。 当然 套路是需要学习去了解,通过实践去掌握的。这和泡妞没啥区别。
那设计模式分几大类呢呢?
1. Creational 创建型设计类: 他们是为了帮助有效的创建对象,让我们使用最少的依赖在类与类之间,同时还能达到最大的代码重用
2. Structural 结构性设计类: 他们可以帮助我们更有效的结构化我们的类,让类之间的关系更加简洁,更加直接
3. Behavioral 行为设计类: 行为设计类型 让我们更加有效,安全的发送不同的行为在不同的程序对象之间
是不是有点云里雾里的啊? 稍安勿躁 让我们细细说来。当然由于时间关系今天我们先说第一种类型(Creational)
第一种: 工厂方法
![](https://img.haomeiwen.com/i14075492/133b550c3269040e.png)
意图:
Factory Method is a creational design pattern that provides an interface for creating objects in superclass, but allow subclasses to alter the type of objects that will be created.
Problem:
Imagine that you are creating a logistics management application. The first version of your app can handle only transportation by trucks, so the bulk of your code lives in a Truck class.
After a while, your app becomes so popular that you get tons of requests to include sea transportation as well.
![](https://img.haomeiwen.com/i14075492/385644db4bdb12c4.png)
Great news, right?! But how about the code? It looks that most of your code is coupled to the Truck class. Adding Ships would require making changes to the entire codebase. Moreover, if you decide to add another type of transportation to the app, you will probably need to make all of those change again.
You will end up with nasty code riddled with conditionals, which select behaviors depending on classes of transport objects.
Solution:
The Factory Method pattern suggests replacing direct object creation (using a new operator) with a call to a special "factory" method. The constructor call should be moved inside that method. Objects returned by factory methods are often referred to as "products."
At first glance, such move may seem pointless. But now you can override the factory method in a subclass and change the class of an object that will be created. Let's see how it works:
![](https://img.haomeiwen.com/i14075492/a9627b1e56e9ba1a.png)
Of course, there is slight limitation: all products must have a common interface (say, Transport). Factory method in a base class should be returning this common interface.
![](https://img.haomeiwen.com/i14075492/afafdfa4a838ef51.png)
Subclasses may return different concrete products as long as these products have a common base class or interface (for example, both Truck and Shipimplement the Transport interface).
![](https://img.haomeiwen.com/i14075492/762b87ca55f4818e.png)
Structure
1.Product declares the single interface for all objects that can be produced by the creator and its subclasses.
2.Concrete Products are the different implementations of the Product interface.
Concrete Creators will create and return instances of these classes.
3.Creator declares a factory method that returns the Product type. This method can either be abstract or have some default implementation. In the first case, all Concrete Creators must implement their factory methods.
Despite the name, in the real world, the product creation is not the main responsibility of a Creator class. Usually, it has some core business logic that works with Products.
Here is the analogy: a large software development company can have a training department for programmers. But the primary function of the company is still writing code.
4. Concrete Creators implement or override the base factory method, by creating and returning one of the Concrete Products.
Note that a factory method does not have to create new instances all the time. It can also return existing objects from some cache, etc.
![](https://img.haomeiwen.com/i14075492/6953c4ec435a135b.png)
Pseudocode:
This example illustrates how Factory Method can be used for creating cross-platform UI elements. The factory method is declared in the base UI dialogue class. It returns abstract buttons. The dialog subclasses override the factory method by returning particular variations of buttons.
![](https://img.haomeiwen.com/i14075492/649952027468c4d7.png)
The result is used in the base dialog's code to compose a UI window. The dialog works with buttons through their common interface. So whichever type of buttons the factory method returns, the dialog code remains functional.
Therefore, the Factory Method pattern makes the primary code of a class independent from the concrete classes of products it uses. Factory Method makes subclasses responsible for choosing concrete classes of products that will be created.
How to Implement
1.Extract the common interface for all products. This interface should declare methods that make sense for every product.
2.Add an empty factory method inside the creator class. Its signature should return the product interface type.
3.Go over the creator's code and find all references to product constructors. One by one, replace them with calls to the factory method but extract product creation code to the factory method.
You might need to add a temporary parameter to the factory method that will be used to control which product will be created.
At this point, the factory method's code may look pretty ugly. It may have a large switch operator that picks which product class will be instantiated. But do not worry, we will fix it right away.
4.Now, override the factory method in subclasses and move there the appropriate case from the switch operator in the base method.
5.The control parameter used in the base creator's class can also be used in subclasses.
For instance, you may have a creator's hierarchy with a base class Mail and classes Air and Ground, plus the product classes: Plane, Truck and Train. Air matches Plane just fine, but Ground matches both Truckand Train at the same time. You can create a new subclass to handle both cases, but there is another option. The client code can pass an argument to the factory method of the Ground class to control which product it receives.
6. If the base factory method has become empty after all moves, you can make it abstract.
Pros and Cons
Follows the Open/Closed Principle.
Avoids tight coupling between concrete products and code that uses them.
Simplifies code due to moving all creational code to one place.
Simplifies adding new products to the program.
Relations with Other Patterns
1.Often, designs start out using Factory Method (less complicated, more customizable via subclasses) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, but more complex) as the designer discovers where more flexibility is needed.
2.Abstract Factory classes are often implemented with Factory Methods, but they can also be implemented using Prototype.
3.Factory Method can be used along with the Iterator pattern to let collection subclasses return proper iterators.
4.Prototype doesn't require subclassing, but it does require an "initialize" operation. Factory Method requires subclassing, but doesn't require initialization step.
5. Factory Method is a specialization of Template Method. On the other hand, Factory Methods often serve as a step in a large Template Method.
网友评论