Design Patterns (II) - Factory mode

Factory Pattern

Define an interface for creating an object, but let subclasses decide which class of instances. Factory method is an example of a class of delay to subclasses.

Factory method may be decoupled to reduce repetitive code.

Factory pattern classification

  1. Simple Factory: static factory method, a module requires only a factory class, it is not necessary to produce it.
  2. Factory method: a plurality of plant
  3. Abstract Factory: Provide an interface for the creation of a group of related or dependent objects, but without specifying their concrete classes.

Code: GitHub

Simple factory method

A module requires only a factory class, it is not necessary to produce it, use static methods on it. In less need to create an object, when the caller is relatively simple to use.

The disadvantage is extended factory class is difficult, it does not comply with the principle of opening and closing (by reflection method can create an instance)

The definition of a class of animals:

public class Animal {
    public void howl() {}
}

Define a class that inherits animal cat:

public class Cat  extends Animal{
    @Override
    public void howl() {
        System.out.println("猫在喵喵叫");
    }
}

The definition of a dog inherits Animal:

public class Dog extends Animal{
    @Override
    public void howl() {
        System.out.println("狗在汪汪叫");
    }
}

Create an animal facility:

public class AnimalFactory {
    public static Object createAnimal(Class<? extends Animal> clazz){
        Object obj = null;
        try {
            obj = Class.forName(clazz.getName()).newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return obj;

    }
}

Factory class instance created by the reflection method.

Factory Method

No longer provides a unified class factory to create all the objects, but to provide different factories for different objects. That is, each object has a corresponding factory with.

advantage:

  • The caller does not need to know the class name specific product category, you only need to know the plant can be.
  • Abstract factory class need only provide an interface to the subclass to create specific objects.

Disadvantages:

  • Scalability and maintainability unfriendly. If you want to extend a product category, we need to create a corresponding factory class, which increases the difficulty of extensions. Because the factory class and the same number of product categories, we need to consider the relationship between the two objects maintenance.

The definition of an animal abstract class:

public abstract class AbstractAnimal {

    /**
     * 所有动物都会叫,叫声不同
     */
    public abstract void howl();
}

A factory producing animals:

public interface AnimalFactory {
    /**
     * 获取一个动物
     * @return
     */
    AbstractAnimal createAnimal();
}	

Cats and dogs factories:

public class CatFactory implements AnimalFactory {
    @Override
    public AbstractAnimal createAnimal() {
        return new Cat();
    }
}


public class DogFactory implements AnimalFactory {
    @Override
    public AbstractAnimal createAnimal() {
        return new Dog();
    }
}

Abstract Factory Method

There are multiple business types and classification, it can produce the required object abstract factory pattern.

The difference between abstract factory and factory method:

Abstract factory is the production of construction products division of products, factory methods only generate a single product. With cats and dogs, for example, now to distinguish between male and female. That there are male and female cats and male dogs and bitches. Each product more than a layer constraints.

advantage:

  • Encapsulation. How does the relationship object is created.
  • Product Constrained a non-public, the family specific product constrained within the factory implementation.

Disadvantages:

  • Product family expansion difficult. Add a product, an abstract class will be more than one way. But the product level is relatively easy to expand. For example animal sex types add a factory, and more than is necessary to achieve an abstract factory class. If you want to increase an animal only need to add a subclass of it.

Extended factory method

1, instead of the single-mode embodiment, the plant can use a simple method of creating a singleton by reflection. The frame may continue to expand, can generate a single embodiment is configured in a project, all classes needed to produce a single embodiment of the follow certain rules (constructor is Private), then by expanding the frame, simply enter a type can be obtained only one instance.

public class Singleton {
    private Singleton(){}

    public void doSomething(){
        System.out.println("工厂方法创建的单例模式");
    }

}

Create a singleton with a simple factory method

public class SingletonFactory {
    private static Singleton singleton;
    static{
        try {
            Class cl= Class.forName(Singleton.class.getName());
            //获得无参构造
            Constructor constructor=cl.getDeclaredConstructor();
            //设置无参构造是可访问的
            constructor.setAccessible(true);
            //产生一个实例对象
            singleton = (Singleton)constructor.newInstance();
        } catch (Exception e) {
            //异常处理
            System.out.println("异常");
        }
    }
    public static Singleton getSingleton(){
        return singleton;
    }

}

2, the delay initialization: After an object is finished consumer does not immediately released, the factory class to maintain its initial state, waiting to be used again. Initializing a delay is extended application of factory methods.

public class ProductFactory {
    private static final Map<String,Product> prMap = new HashMap<>();
    public static synchronized Product createProduct(String type) throws Exception{
    Product product =null;
    //如果Map中已经有这个对象
    if(prMap.containsKey(type)){
            product = prMap.get(type);
        }else{
            if(type.equals("Product1")){
                product = new ConcreteProduct1();
            }else{
                product = new ConcreteProduct2();}
            //同时把对象放到缓存容器中
            prMap.put(type,product);
        }
            return product;
    }
}    

Loading frame delay may be extended, for example to limit the maximum number of instances of a certain class of products, it can be achieved by determining the number of objects existing in the Map, such treatment is very significant, for example JDBC database connection, will require MaxConnections provided a maximum number of connections, the maximum number is the number of memory instances.

Lazy loading can also be used in the object initialization more complex situations, such as hardware access, multi-faceted interaction, you can lazily reducing the complexity of the production and destruction of objects brought.

to sum up

Factory method object model is a new alternative, it can be used in all places the object needs to be generated, but need to carefully consider whether to add a management class factory, increase the complexity of the code.

Require flexible, when the extensible framework, consider using factory methods. Everything Is an Object, that things will all product categories, such as the need to design a frame connected to the mail server, network protocols, there are three to choose from: POP3, IMAP, HTTP, we can put three connection methods as a product category, defined as an interface IConnectMail, and then define a method for the operation of the message, to achieve three specific product class (i.e. connections) further defines a factory method in different ways, according to different incoming conditions, select different connection.


Welcome to public concern number:
No micro-channel public

Guess you like

Origin blog.csdn.net/qq_36447151/article/details/91777690