Java design pattern (3): Abstract Factory pattern (Abstract Factory)

Source: Internet
Author: User

Overview

In software systems, there are often "a series of mutually dependent objects". At the same time, due to changes in requirements, there are often more series of objects to be created. How to deal with this change? How to bypass the conventional object creation method (New), Provides a "encapsulation mechanism" to avoid the tight coupling between the customer program and the "Multi-series object creation work? This is the abstract factory model we want to talk about.

Intention

Provides an interface for creating a series of related or mutually dependent objects without specifying their specific classes.

Model Diagram

Logical Model:

Physical Model:


Implementation points

The abstract factory delays the creation of product objects to subclass of its specific factory. If there is no need to cope with the changes in the "Multi-series object creation", there is no need to use the abstract factory mode. In this case, a simple static factory is enough. A series object refers to the relationship between these objects, such as the dependency between "road" and "House" in game development scenarios, "road" and "authentic" dependencies. Abstract Factory patterns are often combined with factory method patterns to cope with the changes in "Object creation" requirements. Generally, an instance of a specific factory class is created at runtime. The creation of a specific factory has a specific implementation product object. To create different product objects, the customer should use different specific factories. The factory is used as a single piece. In an application, generally each product series only needs a specific factory instance. Therefore, the factory is usually best implemented as a single piece mode. When creating a product, the abstract factory declares only one interface for creating a product. A product is created by a specific product category. The most common method is to define a factory method for each product, A specific factory will redefine the factory method for each product to specify the product. Although this implementation is very simple, it does require that each product series have a new factory subclass, even if there is little difference between these product series.

Advantages

Separates specific classes. Abstract Factory mode helps you control the classes of objects created by an application, because a factory encapsulates the responsibilities and processes of creating product objects. It separates the implementation of customers and classes. The customers manipulate instances through their abstract interfaces, and the product class names are also separated in the implementation of specific factories. They do not appear in the Customer Code. It makes product series Easy to switch. A specific factory class only appears once in an application -- that is, when it is initialized. This makes it easy to change the specific factory of an application. It only needs to change the specific factory to use different product configurations. This is because an abstract factory creates a complete product series, so the entire product series will change immediately. It facilitates product consistency. When a series of product objects are designed to work together, an application can only use objects in the same series at a time. This is very important, and abstract factories can easily achieve this.

Disadvantages

It is difficult to support new types of products. It is difficult to expand abstract factories to produce new types of products. This is because several abstract factory ports determine the product set that can be created. To support new types of products, you need to expand the factory interface, which involves changes to the abstract factory class and all its subclasses.

Applicability

Abstract Factory models should be considered in the following situations:

A system should not depend on the details of how product instances are created, combined, and expressed. This is important for all forms of factory models. This system has more than one product family, and the system only consumes one of them. Products belonging to the same product family are used together. This constraint must be reflected in the system design. The system provides a product library. All products use the same interface, so that the client does not rely on implementation.

Application scenarios

Supports a variety of visual standard user interface toolkit ). Multi-style series scenarios in game development, such as roads, houses, and pipelines. ...... The Code is as follows: Abstract Product role (we have defined a printer)
public abstract class Printer{public abstract void out();public abstract void getData(String msg);}

Abstract Factory role
public interface PrinterFactory{public Printer getPrinter(String type);}

Specific factory roles (we define four specific factories, one is the high-speed printer factory, one is the general printer factory, one is the Dell printer factory, and the other is the HP printer factory)
/** A. High-speed Printer factory * B. It can be Dell or HP */public class BetterPrinterFactory implements PrinterFactory {public Printer getPrinter (String type) {if (type. equals ("dell") {return new DellBetterPrinter ();} else if (type. equals ("hp") {return new HpBetterPrinter ();} else {return null ;}}/ ** a. The factory that produces General Printers * B. It can be Dell, it can also be HP */public class CommonPrinterFactory implements PrinterFactory {public Printer getPrinter (String type) {if (type. equals ("dell") {return new DellCommonPrinter ();} else if (type. equals ("hp") {return new HpCommonPrinter () ;}else {return null ;}}} /** a. Dell Printer factory * B. High-speed Printer or common Printer */public class DellPrinterFactory implements PrinterFactory {public Printer getPrinter (String vendor) {if (vendor. equals ("better") {return new DellBetterPrinter ();} else if (vendor. equals ("common") {return new DellCommonPrinter () ;}else {return null ;}}} /** a. The factory that produces the HP Printer * B. It can be a high-speed Printer or a common Printer */public class HpPrinterFactory implements PrinterFactory {public Printer getPrinter (String vendor) {if (vendor. equals ("better") {return new HpBetterPrinter ();} else if (vendor. equals ("common") {return new HpCommonPrinter () ;}else {return null ;}}}

Specific product roles (we define four products. Dell high-speed printer, Dell general printer, HP high-speed printer, HP general printer)
/*** Dell high-speed Printer */public class DellBetterPrinter extends Printer {private final int MAX_CACHE_LINE = 10; private String [] printData = new String [MAX_CACHE_LINE * 2]; private int dataNum = 0; @ Overridepublic void getData (String msg) {if (dataNum> = MAX_CACHE_LINE * 2) {System. out. println ("the output queue is full, adding failed");} else {printData [dataNum ++] = msg ;}@ Overridepublic void out () {while (dataNum> 0) {System. out. println ("Dell high-speed printer printing:" + printData [0]); System. arraycopy (printData, 1, printData, 0, -- dataNum) ;}}/ *** Dell Printer */public class DellCommonPrinter extends Printer {private final int MAX_CACHE_LINE = 10; private String [] printData = new String [MAX_CACHE_LINE]; private int dataNum = 0; @ Overridepublic void getData (String msg) {if (dataNum> = MAX_CACHE_LINE) {System. out. println ("the output queue is full, adding failed");} else {printData [dataNum ++] = msg ;}@ Overridepublic void out () {while (dataNum> 0) {System. out. println ("Dell printer print:" + printData [0]); System. arraycopy (printData, 1, printData, 0, -- dataNum) ;}}/ *** HP high-speed Printer */public class HpBetterPrinter extends Printer {private final int MAX_CACHE_LINE = 10; private String [] printData = new String [MAX_CACHE_LINE * 2]; private int dataNum = 0; @ Overridepublic void getData (String msg) {if (dataNum> = MAX_CACHE_LINE * 2) {System. out. println ("the output queue is full, adding failed");} else {printData [dataNum ++] = msg ;}@ Overridepublic void out () {while (dataNum> 0) {System. out. println ("HP high-speed printer printing:" + printData [0]); System. arraycopy (printData, 1, printData, 0, -- dataNum) ;}}/ *** HP Printer */public class HpCommonPrinter extends Printer {private final int MAX_CACHE_LINE = 10; private String [] printData = new String [MAX_CACHE_LINE]; private int dataNum = 0; @ Overridepublic void getData (String msg) {if (dataNum> = MAX_CACHE_LINE) {System. out. println ("the output queue is full, adding failed");} else {printData [dataNum ++] = msg ;}@ Overridepublic void out () {while (dataNum> 0) {System. out. println ("HP printer print:" + printData [0]); System. arraycopy (printData, 1, printData, 0, -- dataNum );}}}

Create a desired factory to produce the corresponding printer
/** Create a desired factory to produce the corresponding printer */public class PrinterFactoryFactory {public PrinterFactory getPrintFactory (String type) {if (type. equals ("common") // create a factory that produces a common printer {return new CommonPrinterFactory ();} else if (type. equals ("better") // create a factory that produces high-speed printers {return new BetterPrinterFactory ();} else if (type. equals ("dell") // create a factory that produces dell printers {return new DellPrinterFactory (); // create a factory that produces HP printers} else if (type. equals ("hp") {return new HpPrinterFactory () ;}else {return null ;}}}



Finally, we tested it. we defined a computer that calls the factory to produce the printer we needed. What kind of printers are needed? You only need to obtain the corresponding type of factory for production, and then the factory will produce the specific printer. Here we have four types of factories. For example, 1) HP's headquarters can have a factory that can produce general or high-speed printers of the HP brand: 2) dell also has a factory in its headquarters that can produce general or high-speed printers of the HP brand: 3) However, some high-end foundry companies are willing to produce printers for those large companies, there is a low-end factory dedicated to the production of General printers, which can produce low-end printers of HP and Dell models; 4) Of course there are also high-end manufacturers, produce their high-end brands for HP and Dell.
Here, no matter what brand or type of printer we need, we can either get it at the factory of this brand or at the high-end or low-end foundry.
public class Computer{private Printer out;public Computer(Printer out){this.out = out;}public void keyIn(String msg){out.getData(msg);}public void print(){out.out();}public static void main(String[] args){PrinterFactoryFactory pff = new PrinterFactoryFactory();PrinterFactory of = pff.getPrintFactory("common");Computer c = new Computer(of.getPrinter("hp"));c.keyIn("hello");c.keyIn("world");c.print();PrinterFactoryFactory pff2 = new PrinterFactoryFactory();PrinterFactory of2 = pff2.getPrintFactory("hp");Computer c2 = new Computer(of2.getPrinter("common"));c2.keyIn("hello");c2.keyIn("world");c2.print();}}

Output: HP printer print: hello
HP printer print: world

HP printer print: hello
HP printer print: world

Summary

In short, the abstract factory model provides an interface for creating a series of related or mutually dependent objects. The key point of using the abstract factory model is to cope with the changes in the demand for "Multi-series object creation. After learning the abstract factory model, you will understand the essence of OOP: interface-oriented programming.



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.