"51" Java design pattern-analysis of factory design patterns

Source: Internet
Author: User

Classification of plant design and design patterns: The factory model is divided into three categories in Java and mode:

1) Simple Factory mode (simply Factory): not conducive to the production of products;

2) Factory method mode (Factory): Also known as the polymorphism plant;

3) Abstract Factory mode (abstract Factory): Also known as the toolbox, producing product families, but not conducive to the production of new products;

These three modes are progressively abstracted from top to bottom and more general.

In design mode, GOF divides the factory model into two categories: The Factory method Model (Factory) and the Abstract Factory mode (abstraction Factory). The simple Factory is seen as a special case of the factory method pattern, which is grouped into one category.

Example:

1) There is no factory era: if there is no industrial revolution, if a customer wants a BMW, the general practice is to create a BMW car, and then to use.
2) Simple Factory mode: Later the Industrial Revolution occurred. Users do not have to create a BMW car. Because the customer has a factory to help him create a BMW. The factory can be built if you want a car. For example, want 320i series cars. The factory created this series of cars. That is, the factory can create products.
3) Factory method Mode era: In order to meet customers, BMW series more and more, such as 320i,523i,30li series of a factory can not create all the BMW series. It is then separated from a number of specific factories. Each specific factory creates a series. That is, the specific factory class can only create a specific product. But the BMW factory is still an abstraction. You need to designate a specific factory to produce the car.
4) Abstract Factory mode era: With the increasing demands of customers, BMW must be equipped with air-conditioning. So the factory started to produce BMW cars and needed air conditioners.

In the end, the customer just said to the BMW salesman: "I want 523i air-conditioned car, the salesman will give him 523i air-conditioned car directly." Instead of creating a BMW 523i air-conditioned car yourself.

This is the factory model.

Difference:

Factory method Mode:
An abstract product class that can derive a number of specific product classes.
An abstract factory class that can derive a number of specific factory classes.
Each specific factory class can only create an instance of a specific product class.
Abstract Factory mode:
Multiple abstract product classes, each abstract product class can derive multiple specific product classes.
An abstract factory class that can derive a number of specific factory classes.
Each specific factory class can create instances of more than one specific product class.
Difference:
The factory method pattern has only one abstract product class, and the abstract factory pattern has multiple.
Factory-mode-specific factory classes can only create instances of a specific product class, while abstract Factory mode may create multiple.
Both are available.

Simple Factory mode

 Public classBMW320 { Public BMW320() {System. out. println ("Manufacturing-->bmw320"); }  } Public classBMW523 { Public BMW523() {System. out. println ("Manufacturing-->bmw523"); }  } Public classCustomer { Public Static void Main(string[] args) {BMW320 bmw320 =NewBMW320 (); BMW523 bmw523 =NewBMW523 (); }  }
The operation details of the creation of the BMW are put into the factory, the customer directly uses the factory to create the factory method, incoming the desired BMW model is OK, without having to know the details of the creation. This is the Industrial Revolution: Simple Factory mode

Product class: [Java] View plain copy print? View the code snippet from my Code sliceAbstractClass BMW { Public BMW(){      }  } Public  class BMW320 extends BMW {       Public BMW320() {System.out.println ("Manufacturing-->bmw320"); }  } Public  class BMW523 extends BMW{       Public BMW523() {System.out.println ("Manufacturing-->bmw523"); }} factory class: [Java] View plain copy print? On code to view the snippet derived from my Code slice Public  class Factory {       PublicBMWCREATEBMW(intType) {Switch(type) { Case  the:return NewBMW320 (); Case 523:return NewBMW523 ();default: Break; }return NULL; }} Client class: [Java] View plain copy print? View the code slice to derive from my code slice Public  class Customer {       Public Static void Main(string[] args) {Factory Factory =NewFactory (); BMW bmw320 = FACTORY.CREATEBMW ( the); BMW bmw523 = FACTORY.CREATEBMW (523); }  }
It consists of:

1) Factory class role: This is the core of this model, contains certain business logic and judgment logic, used to create the product
2) Abstract Product role: It is generally the product of the specific inheritance of the parent class or implementation of the interface.
3) Specific product roles: the object created by the factory class is an instance of this role. Implemented in Java by a concrete class.

When a new car is added, the code needs to be updated to support the new car. This violates the opening and shutting principle (Open-close Principle). You can use Reflection (Reflection) to resolve the problem. Use Reflection for Extensibility:

"'
public class CarFactory2 {

private static final Logger LOG = Loggerfactory.getlogger (Carfactory2.class);

public static Car Newcar () {
Car car = null;
String name = NULL;
try {
xmlconfiguration config = new Xmlconfiguration ("Car.xml");
Name = Config.getstring ("Factory2.class");
} catch (ConfigurationException ex) {
Log.error ("Parsing XML configuration file failed", ex);
}

try {  car = (Car)Class.forName(name).newInstance();  LOG.info("Created car class name is {}", name);} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {  LOG.error("Instantiate car {} failed", name);}return car;

}

}

As you can see from the code above, if you need to introduce a new car, just specify the full class name of the car in the configuration file (including the package name), and CarFactory2 can instantiate it by reflection. The opening of the extension is achieved, while the closure of the modification is ensured. Readers familiar with spring should think of the spring IOC implementation.Simple Factory mode benefits:---------1. Factory class is the key to the entire simple factory model. It contains the necessary judgment logic to determine which specific class of objects should be created, based on information given by the outside world (configuration, or parameters). Users can create the required instances directly from the factory class, without having to know how they are created and how they are organized. facilitates the optimization of the entire software architecture. 2. By introducing configuration files and reflections, you can change and add new product classes without modifying any client code, to some extent improving system flexibility (such as CarFactory2). 3. The client does not need to know the class name of the specific product class created, only need to know the specific product class corresponding parameters, for some complex class names, through the simple Factory mode can reduce the user's memory (such as CarFactory3).Simple Factory mode disadvantage:---------1. Because the factory class centralizes the creation logic of all instances, this directly leads to the involvement of all clients once the factory has a problem. 2. Since the products of the simple factory model are based on a common abstract class or interface, so that when the type of product is increased, that is, when there are different product interfaces or abstract classes, the factory class needs to determine when the product of the interface is created, which is confused with what kind of product is created. Violates the principle of single responsibility, resulting in loss of flexibility and maintainability of the system. 3. As mentioned above, in general (e.g. CarFactory1), the simple factory model violates the "open-close principle" because when we add a new product we must modify the factory class, and the corresponding factory class will need to be recompiled again. But this can be solved to some extent (such as CarFactory2) using reflection (CarFactory3 is also using reflection in nature). Using reflection allows a simple factory to satisfy the "open-close principle" under certain conditions, but this is limited to the construction of the product class and the initialization of the same scenario. For each product instantiation or initializing different scenarios, it is difficult to use reflection to satisfy the "open-close" principle. 4. Simple Factory mode due to the use of the static factory method, the factory role cannot form an inheritance-based hierarchy. This is a reservation, because inheritance is not an end, and if there is no such requirement, it is not a disadvantage, such as the DriverManager of JDBC.Factory method Mode: = =The factory method pattern removes the static property of the factory method in the simple Factory mode, allowing it to inherit from the quilt class. The pressure to concentrate on factory methods in a simple factory model can be shared by different factory subclasses in the factory method model. Factory Method Pattern Composition:---------1) Abstract Factory role: This is the core of the factory method pattern, which is independent of the application. is the interface that the specific factory role must implement or the parent class that must inherit. In Java it is implemented by an abstract class or interface. 2) Specific factory role: it contains code related to the specific business logic. Called by the application to create an object that corresponds to a specific product. 3) Abstract product role: It is the parent of a specific product inheritance or an interface implemented. In Java, there are generally abstract classes or interfaces to implement. 4) Specific product roles: the object created by the specific factory role is an instance of this role. Implemented in Java by a specific class. The factory method pattern uses multiple subclasses that inherit from the abstract factory role to replace the "God Class" in the simple factory pattern. As mentioned above, this shares the pressure of the object, and this makes the structure flexible--when a new product is produced, it can be used by the customer as long as it is generated by the contract provided by the abstract product role and the abstract factory role, without having to modify any existing code. We can see that the structure of the factory role is also in line with the closed principle! 

Product Category:

[Java] View plain copy print? On code to view a snippet derived from my Code slice
Abstract class BMW {
Public BMW () {

}  

}
public class BMW320 extends BMW {
Public BMW320 () {
System.out.println ("Manufacturing –>bmw320");
}
}
public class BMW523 extends bmw{
Public BMW523 () {
System.out.println ("Manufacturing –>bmw523");
}
}

To create a factory class:

[Java] View plain copy print? On code to view a snippet derived from my Code slice
Interface FACTORYBMW {
BMW CREATEBMW ();
}

public class FactoryBMW320 implements factorybmw{

@Override  public BMW320 createBMW() {      return new BMW320();  }  

}
public class FactoryBMW523 implements FACTORYBMW {
@Override
Public BMW523 CREATEBMW () {

    return new BMW523();  }  

}

Customer class:

[Java] View plain copy print? On code to view a snippet derived from my Code slice
public class Customer {
public static void Main (string[] args) {
FactoryBMW320 factoryBMW320 = new FactoryBMW320 ();
BMW320 bmw320 = FACTORYBMW320.CREATEBMW ();

    FactoryBMW523 factoryBMW523 = new FactoryBMW523();      BMW523 bmw523 = factoryBMW523.createBMW();  }  

}

抽象工厂模式:==当每个抽象产品都有多于一个的具体子类的时候(空调有型号A和B两种,发动机也有型号A和B两种),工厂角色怎么知道实例化哪一个子类呢?比如每个抽象产品角色都有两个具体产品(产品空调有两个具体产品空调A和空调B)。抽象工厂模式提供两个具体工厂角色(宝马320系列工厂和宝马230系列工厂),分别对应于这两个具体产品角色,每一个具体工厂角色只负责某一个产品角色的实例化。每一个具体工厂类只负责创建抽象产品的某一个具体子类的实例。## 抽象工厂模式代码 ##

Product Category:

[Java] View plain copy print? On code to view a snippet derived from my Code slice
Engine and model
Public interface Engine {

}
public class Enginea extends engine{
Public Enginea () {
System.out.println ("Manufacturing –>enginea");
}
}
public class Enginebextends engine{
Public Engineb () {
System.out.println ("Manufacturing –>engineb");
}
}

Air Conditioning and model
Public interface Aircondition {

}
public class Airconditiona extends aircondition{
Public Airconditiona () {
System.out.println ("Manufacturing –>airconditiona");
}
}
public class Airconditionb extends aircondition{
Public airconditionb () {
System.out.println ("Manufacturing –>airconditionb");
}
}

To create a factory class:

[Java] View plain copy print? On code to view a snippet derived from my Code slice
Create a factory interface
Public interface Abstractfactory {
Manufacturing Engines
Public Engine createengine ();
Manufacturing Air Conditioning
Public aircondition createaircondition ();
}

Production accessories for BMW 320 series
public class FactoryBMW320 implements abstractfactory{

@Override    public Engine createEngine() {          return new EngineA();    }    @Override    public Aircondition createAircondition() {        return new AirconditionA();    }    

}
BMW 523 Series
public class FactoryBMW523 implements Abstractfactory {

 @Override    public Engine createEngine() {          return new EngineB();    }    @Override    public Aircondition createAircondition() {        return new AirconditionB();    }    

}

Customer:

[Java] View plain copy print? On code to view a snippet derived from my Code slice
public class Customer {
public static void Main (string[] args) {
Production of BMW 320 series Accessories
FactoryBMW320 factoryBMW320 = new FactoryBMW320 ();
Factorybmw320.createengine ();
Factorybmw320.createaircondition ();

    //生产宝马523系列配件        FactoryBMW523 factoryBMW523 = new FactoryBMW523();        factoryBMW320.createEngine();      factoryBMW320.createAircondition();  }    

}

"'

Welcome to the group: public number It face questions summary discussion group

If the scan does not go in, add me (rdst6029930) pull you. Sweep my QR code plus me

You are welcome to pay attention to the "It question summary" subscription number. Every day to push the classic face test and interview tips, are dry! The QR code of the subscription number is as follows:

Reference:
http://www.jasongj.com/design_pattern/simple_factory/
http://blog.csdn.net/jason0539/article/details/23020989
http://blog.csdn.net/jason0539/article/details/44976775

"51" Java design pattern-analysis of factory design patterns

Related Article

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.