23 Design Modes (2): Factory method mode

Source: Internet
Author: User

Definition: Defines an interface that is used to create an object, so that subclasses decide which class to instantiate, and the factory method defers the instantiation of a class to its subclasses.

Type: Create class mode

Class Diagram:

Factory Method Pattern Code

Interfaceiproduct {public void Productmethod (); }ClassProductImplementsiproduct {public void Productmethod () {System.out.println ( "products"); }} interface IFactory {public iproduct createproduct (); } class factory implements ifactory {public IProduct createproduct () {return new Product ();} public class Client { public static void Main (string[] args) {Ifactory factory = new Factory (); IProduct prodect = Factory.createproduct (); Prodect.productmethod (); } } 

Factory mode:

First, we need to talk about the factory model. The factory model is divided into three different levels of abstraction: the Simple Factory mode (also called the Static Factory mode), the factory method pattern described in this article, and the abstract factory model. Factory mode is a pattern that is often used in programming. Its main advantages are:

You can make your code structure clear and effectively encapsulate changes. In programming, the instantiation of the product class is sometimes more complex and changeable, through the Factory mode, the product instantiation encapsulation, so that the caller does not have to care about the product instantiation process, just rely on the factory can get the products they want.

Block specific product classes for callers. If you use Factory mode, the caller only cares about the interface of the product, and as for the specific implementation, the caller doesn't have to care. Even if a specific implementation is changed, it has no effect on the caller.

Reduce the coupling degree. The instantiation of a product class is often complicated, it relies on many classes, and these classes do not need to be known to the caller, and if a factory method is used, all we need to do is instantiate a good product class and then hand it over to the caller. For callers, the classes on which the product depends are transparent.

Factory method Mode:

With the class diagram of the factory method pattern, you can see that the factory method pattern has four elements:

Factory interface. The factory interface is the core of the factory method pattern, which interacts directly with the caller to provide the product. In practical programming, an abstract class is sometimes used as an interface to interact with the caller, essentially the same.

Factory implementation. In programming, the factory implementation decides how to instantiate the product, is the way to realize the expansion, how many kinds of products need to have, how many concrete factories need to implement.

Product interface. The main purpose of the product interface is to define the product specification, and all product implementations must follow the specification of the product interface definition. Product interface is the most concern of the caller, the product interface definition directly determines the stability of the caller code. Similarly, product interfaces can be replaced with abstract classes, but it is best not to violate the Richter scale substitution principle.

Product realization. The specific class that implements the product interface determines the specific behavior of the product in the client.

The simple factory model mentioned earlier is very similar to the factory method pattern, except that there are only three elements in a simple factory, he has no factory interface, and the method of obtaining the product is generally static. Because there is no factory interface, so the scalability of the factory implementation is slightly weaker, can be counted as a simplified version of the factory method model, about the simple factory model, in this one pen.

Applicable scenarios:

Whether it's a simple factory model, a factory method pattern or an abstract factory pattern, they have similar characteristics, so their application scenario is similar.

First, as a way to create a class pattern, you can use the factory method pattern in any place where complex objects need to be generated. One thing to keep in mind is that complex objects are suitable for Factory mode, and simple objects, especially those that can be created only through new, do not need to use Factory mode. If you use Factory mode, you need to introduce a factory class that increases the complexity of the system.

Second, the factory model is a typical decoupling model, and the Dimitri law is particularly evident in the factory model. Consider using Factory mode if the caller is assembling the product to increase dependencies. Will greatly reduce the degree of coupling between the objects.

Again, because the factory model relies on abstract architecture, it puts the task of instantiating the product into the implementation class, which is better. That is to say, when the need for better scalability of the system, you can consider the factory model, different products with different implementation of the factory to assemble.

Typical applications

To illustrate the advantages of the factory model, there may be no more suitable example than assembling a car. The scene is this: The car consists of an engine, a wheel, a chassis, and now needs to assemble a car to the caller. If you do not use Factory mode, the code is as follows:

Class Engine {PublicvoidGetStyle () {System.Out.println ("This is the engine of the car"); }} class Underpan {Publicvoid getstyle () {system. Out.println ( "This is the chassis of the Car");}} Class Wheel {public void getStyle () {System. out.println ( "This is the tyre of the Car");}} public class Client {public static void main (String[] args) {Engine Engine = new engine (); Underpan Underpan = new Underpan (); Wheel Wheel = new Wheel (); ICar car = new car (underpan, wheel, Engine); Car.show ();}}     

As you can see, the caller also needs to instantiate the engine, chassis and tires in order to assemble the car, and the components of these cars are not related to the caller, they violate the Dimitri law, and the coupling is too high. and is very detrimental to expansion. In addition, in this case the engine, chassis and tires are more specific, in practical applications, may be the components of these products are also abstract, the caller does not know how to assemble the product. If the factory method is used, the whole structure will be much clearer.

Interfaceifactory {Public ICar Createcar (); }class factory implements ifactory {public ICar Createcar () {Engine engine = new engine (); Underpan Underpan = new Underpan (); Wheel Wheel = new Wheel (); ICar car = new car (underpan, wheel, engine); return car;} } public class client {public static void Main ( String[] args) {Ifactory factory = new factory (); ICar car = Factory.createcar (); Car.show (); } } 

After using the factory method, the coupling degree of the caller is greatly reduced. And for the factory, can be extended, and later if you want to assemble other cars, only need to add a factory class to achieve. Both flexibility and stability have been greatly improved.

23 Design Modes (2): Factory method mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.