Design Patterns: simple factory pattern

Simple factory pattern

concept

Simple factory pattern to create a schema belong, also known as static factory method (Static Factory Method). Simple factory pattern is determined by a factory object which created a product class instance. In the simple mode, the factory can return an instance of a different class according to different parameters. Simple factory pattern to define a special class to other classes responsible for creating an instance, the instance is created normally have a common parent class. Simple factory pattern is the factory model family is the most simple and practical model can be understood as a special mode of realization of different plants

It is worth noting that a simple factory pattern does not belong to one of GOF design patterns. But he said the basis of the abstract factory pattern, factory method pattern, and there was a wide range of applications

Mode structure

composition

As can be seen from the figure above, simple factory pattern consists of three parts: the concrete factory, the abstract and concrete products Product :

  • Factory class (Creator): This is the core of this mode, it contains a certain business logic and arbitration logic. In java, it is often implemented by a specific class
  • Abstract product (AbstractProduct): It is generally specific products inherit the parent class or implement the interface. In Java, the interface implemented by the abstract class or
  • Specific products (ConcreteProduct): Object factory class is created instance of this role. Realized by a specific class in java

Case Analysis

Requirements: There are apples and bananas class class, they have a get method, they are instantiated by the main function, and call the get method

Method 1: The most basic instantiation

Apple.java:
public class Apple {
    /**
     * 采集苹果
     */
    public void get(){
        System.out.println("采集苹果");
        }
}
Banana.java:
public class Banana {
    /**
     * 采集香蕉
     */
    public void get(){
        System.out.println("采集香蕉");
    }
}
MainClass.java:
public class Mainclass{
    public static void main(String[] args){
        /**
         * 最基本的实例化方式
         */
        //实例化一个Apple
        Apple apple = new Apple();
        //实例化一个Banana
        Banana banana = new Banana();
        
        apple.get();
        banana.get();
    }
}

Second way: both get method, we can implement an interface that class with a polymorphic manner

Fruit.java:
public interface Fruit {
    public void get();
}
Apple.java:
public class Apple implements Fruit{
    @Override
    //重写get方法
    public void get(){
        System.out.println("采集苹果");
    }
}
Banana.java:
public class Banana implements Fruit{
    @Override
    //重写get方法
    public void get(){
        System.out.println("采集香蕉");
    }
}
MainClass.java:
public class Mainclass{
    public static void main(String[] args){
        /**
         * 多态的实例化方式
         */
        Fruit apple = FruitFactory.getApple();
        Fruit banana = FruitFactory.getBanana();

        apple.get();
        banana.get();
    }
}

Three ways: a new factory and create a class that implements the main logic objects

FruitFactory:
public class FruitFactory {
    /**
     * 获得Apple类的实例
     */
    public static Fruit getApple(){
        return new Apple();
    }

    /**
     * 获得Banana类的实例
     */
    public static Fruit getBanana(){
        return new Banana();
    }
}
Fruit.java: unchanged
public interface Fruit {
    public void get();
}
Apple.java: unchanged
public class Apple implements Fruit{
    @Override
    //重写get方法    
    public void get(){
        System.out.println("采集苹果");
    }
}
Banana.java: unchanged
public class Banana implements Fruit{
    @Override
    //重写get方法
    public void get(){
        System.out.println("采集香蕉");
    }
}
MainClass.java: unchanged
public class Mainclass{
    public static void main(String[] args){
        /**
         * 通过工厂类的静态方法实例化
         */
        Fruit apple = FruitFactory.getApple();
        Fruit banana = FruitFactory.getBanana();

        apple.get();
        banana.get();
    }
}

Four ways: Optimization of a factory class, call the same method, by way of example of the transmission reference

FruitFactory:
public class FruitFactory {
    public static Fruit getFruit(String type) throws IllegalAccessException, ClassNotFoundException, InstantiationException {
        /**
         * 对参数的判断并返回实例
         */
        if (type.equalsIgnoreCase("apple")){
            return Apple.class.newInstance();
        } else if (type.equalsIgnoreCase("banana")){
            return Banana.class.newInstance();
        } else {
            System.out.println("找不到相应的实例化类");
            return null;
        }
    }
}
Fruit.java: unchanged
public interface Fruit {
    public void get();
}
Apple.java: unchanged
public class Apple implements Fruit{
    @Override
    public void get(){
        System.out.println("采集苹果");
    }
}
Banana.java: unchanged
public class Banana implements Fruit{
    @Override
    public void get(){
        System.out.println("采集香蕉");
    }
}
MainClass.java:
public class Mainclass{
    public static void main(String[] args) throws IllegalAccessException, ClassNotFoundException, InstantiationException {
        Fruit apple = FruitFactory.getFruit("apple");
        Fruit banana = FruitFactory.getFruit("banana");
        apple.get();
        banana.get();
    }
}

Five ways: to optimize factory class II instantiation process further optimize reflected by the class name

FruitFactory:
public class FruitFactory {
    public static Fruit getFruit(String type) throws IllegalAccessException, ClassNotFoundException, InstantiationException {
        
        Class fruit = Class.forName(type);
        return (Fruit)fruit.newInstance();
    }
}
Fruit.java: unchanged
public interface Fruit {
    public void get();
}
Apple.java: unchanged
public class Apple implements Fruit{
    @Override
    public void get(){
        System.out.println("采集苹果");
    }
}
Banana.java: unchanged
public class Banana implements Fruit{
    @Override
    public void get(){
        System.out.println("采集香蕉");
    }
}
MainClass.java:
public class Mainclass{
    public static void main(String[] args) throws IllegalAccessException, ClassNotFoundException, InstantiationException {
        Fruit apple = FruitFactory.getFruit("Apple");
        Fruit banana = FruitFactory.getFruit("Banana");
        apple.get();
        banana.get();
    }
}

advantage

  • Factory class contains the necessary logic judgment, can decide which instance of a product class is created at what time the client may be exempted from the responsibility to create product objects directly, but only "consumer" product; a simple factory pattern achieved through the practice of responsibility the division, which provides specialized factory class for creating an object
  • Clients do not need to know the class name specific product category created only need to know the specific product class corresponding parameters can be, for some complex class name, a simple factory pattern can reduce the amount of user memory
  • By introducing the configuration file, you can change and add new specific product category without modifying any client-side code and improve the flexibility of the system to a certain extent
  • When the need to introduce new products do not need to modify the client code, just add the appropriate product category and modify the factory class on it, so that products from the point of view of a simple factory pattern is consistent with "open - closed" principle

Shortcoming

  • Since the factory class centralizes all product creation logic, our factory class is generally referred to as "all class" or "God class", because all he can to create a complete product, which appears to be a good thing, but think there is a problem of. For example, the whole country has all the things a human stem nationalism would not be a problem, of course! Once does not work, the entire system must be affected
  • Using a simple model will increase the number of factory classes in the system, it increases the complexity and the difficulty of understanding the system in certain procedures
  • System expansion difficult, once the new product will have to add logic to modify the plant, when there are many types of products, may cause the plant logic is too complicated, is not conducive to the expansion and maintenance of the system. So from the point of view of the plant is simple factory pattern is not consistent with "open - closed" principle
  • Simple factory pattern due to the use of static factory method, resulting in the role of the factory can not form a hierarchy based on inheritance

Applicable scene

  1. Object factory class is responsible for creating relatively small: less due to the object created, the factory method will not cause too complex business logic
  2. The client only knows the parameters passed factory class, how to create objects do not care: the client requires neither care about the details of creation, even the name of the class do not need to remember that only need to know the type of the corresponding parameter

Guess you like

Origin www.cnblogs.com/MessiXiaoMo3334/p/11600760.html