The "Factory Model" of Design Patterns Written for Myself

1. Simple factory model

Also known as the static factory method (Static Factory Method) mode, it belongs to the creation mode, which specifically defines a class to be responsible for creating instances of other classes. The created instances usually have a common parent class.

1.1 scene

  • The factory class is responsible for creating fewer objects and will not cause business logic to be too complicated
  • The client only knows the parameters passed into the factory class, and does not care about how to create the class

1.2 Advantages

  • The division of responsibilities is realized, the factory class is responsible for creating product objects, and the client is responsible for "consumption", and there is no need to remember the class name of the product class

1.3 Disadvantages

  • The factory class is responsible for the creation of all products, once it fails to work, it will affect the entire system
  • Violation of the opening and closing principle. Once you need to add products, you need to modify the implementation logic of the factory class. Too many products may cause the factory class logic to be complicated
  • Because the simple factory model uses static factory methods, static methods cannot be inherited or rewritten, which will cause the factory role to fail to form a hierarchy based on inheritance.
1. 创建teacher接口
/**
 * teacher接口,定义方法
 *
 * @author dkangle
 */
public interface Teacher {
    
    
    void teach();
}

2. 实现teacher接口
/**
 * 数学老师
 *
 * @author dkangel
 */
public class MathTeacher implements Teacher {
    
    
    @Override
    public void teach() {
    
    
        System.out.println("I teach math.");
    }
}

/**
 * 英语老师
 *
 * @author dkangel
 */
public class EnglishTeacher implements Teacher {
    
    
    @Override
    public void teach() {
    
    
        System.out.println("I teach english.");
    }
}

3. 创建teacher工厂类,并创建静态方法获取teacher实例
/**
 * teacher工厂类
 * <p>
 * 定义一个工厂类专门实例化teacher实例,这些实例具有相同的父类
 *
 * @author dkangel
 */
public static class TeacherFactory {
    
    
    public Teacher getTeacher(String type) {
    
    
        if ("math".equals(type)) {
    
    
            return new MathTeacher();
        } else if ("english".equals(type)) {
    
    
            return new EnglishTeacher();
        }
        return null;
    }
}

4. 使用
/**
 * 简单工厂使用类
 *
 * @author dkangel
 */
public class Main {
    
    
    public static void main(String[] args) {
    
    
        // 数学老师
        Teacher teacher = TeacherFactory.getTeacher("math");
        teacher.teach();

        // 英语老师
        teacher = TeacherFactory.getTeacher("english");
        teacher.teach();
    }
}

2. Factory method pattern

Also known as factory mode, polymorphic factory mode, and virtual constructor mode, the parent class of the factory is responsible for defining the public interface for creating objects, and the subclass is responsible for generating specific objects.

2.1 Scene

  • When a class does not know the class of the object it needs
  • When a class wants to specify the creation of objects through its subclasses

2.2 Advantages

  • Comply with the opening and closing principle, when adding new products, only need to add specific product categories and factory sub-categories
  • In line with the single responsibility principle, a factory sub-category is only responsible for creating corresponding products
  • Do not use static factory methods, can form a hierarchy based on inheritance

2.3 Disadvantages

  • When adding a new product, in addition to adding a new product category, it is also necessary to provide the corresponding specific factory category. The number of system categories will increase in pairs, which increases the complexity of the system to a certain extent; at the same time, there are more categories. Need to compile and run, will bring some additional overhead to the system
  • Considering the scalability of the system, it is necessary to introduce an abstraction layer, which is defined in the client code, which increases the abstraction and difficulty of understanding the system
  • A specific factory can only create one specific product
1. 创建抽象工厂类
/**
 * teacher接口
 *
 * @author dkangel
 */
public interface Teacher {
    
    
    /**
     * 教学
     */
    void teach();
}

2. 创建抽象teacher类
/**
 * teacher类
 *
 * @author dkangel
 */
public abstract class Teacher {
    
    
    /**
     * 教学
     */
    public abstract void teach();
}

3. 创建具体的teacher类
/**
 * math teacher类
 *
 * @author dkangel
 */
public class MathTeacher implements Teacher {
    
    
    @Override
    public void teach() {
    
    
        System.out.println("I am math teacher.");
    }
}

4. 创建具体工厂类
/**
 * 具体工厂类 math teacher factory
 * 
 * @author dkangel
 */
public class MathFactory extends Factory {
    
    
    @Override
    public Teacher getTeacher() {
    
    
        return new MathTeacher();
    }
}

5. 使用
/**
 * 工厂方法使用类
 *
 * @author dkangel
 */
public class Main {
    
    
    public static void main(String[] args) {
    
    
        // 数学老师
        AbstractFactory factory = new MathFactory();
        Teacher teacher = factory.getTeacher();

        // 英语老师
        factory = new EnglishFactory();
        teacher = factory.getTeacher();
    }
}

3. Abstract factory pattern

Provide an interface to create a series of related or interdependent objects without specifying their specific classes. Create other factories around the super factory

3.1 Scene

  • A system does not require to rely on the expression of how product class instances are created, combined and expressed, which is also the prerequisite for the application of all factory patterns
  • This system has multiple series of products, and only a certain series of products are consumed in the system
  • The system requires a product-like library, all products appear with the same interface, and the client does not need to rely on specific implementations

3.2 Advantages

  • Reduce coupling. The
    abstract factory model delays the creation of specific products to the subclasses of specific factories. This encapsulates the creation of objects, which can reduce the dependence between the client and the specific product class, so that the system coupling is low, which is more Conducive to later maintenance and expansion;
  • More in line with the open-close principle. When
    adding a new product category, you only need to add the corresponding specific product category and the corresponding factory sub-category.
  • Comply with the single responsibility principle.
    Each specific factory class is only responsible for creating corresponding products
  • Without using static factory methods, a hierarchy based on inheritance can be formed.

3.3 Disadvantages

  • The abstract factory model is difficult to support changes in new types of products.
    This is because the abstract factory interface has determined the set of products that can be created. If you need to add new products, you must modify the interface of the abstract factory at this time. This involves the change of the abstract factory class and all subclasses, so It also violates the "development-closed" principle
1. 创建电脑接口
/**
 * 电脑接口
 *
 * @author dkangel
 */
public interface Computer {
    
    
    /**
     * 写代码
     */
    void code();
}

2. 创建电脑实现类
public class HuaweiComputer implements Computer {
    
    
    @Override
    public void code() {
    
    
        System.out.println("Huawei Computer code.");
    }
}
public class AppleComputer implements Computer {
    
    
    @Override
    public void code() {
    
    
        System.out.println("Apple Computer code.");
    }
}

3. 创建手机接口
/**
 * 手机接口
 *
 * @author dkangel
 */
public interface Phone {
    
    
    /**
     * 打电话
     */
    void call();
}

4. 创建手机实现类
public class HuaweiPhone implements Phone {
    
    
    @Override
    public void call() {
    
    
        System.out.println("Huawei Phone call.");
    }
}
public class ApplePhone implements Phone {
    
    
    @Override
    public void call() {
    
    
        System.out.println("Apple Phone call.");
    }
}

5. 创建抽象工厂类
/**
 * 工厂类
 *
 * @author dkangel
 */
public abstract class AbstractFactory {
    
    
    /**
     * 生产手机
     *
     * @return Phone
     */
    public abstract Phone manufacturePhone(String company);

    /**
     * 生产电脑
     *
     * @return Computer
     */
    public abstract Computer manufactureComputer(String company);
}

6. 创建电脑、手机工厂类
/**
 * Computer工厂类
 *
 * @author dkangel
 */
public class ComputerFactory extends AbstractFactory {
    
    
    @Override
    public Phone manufacturePhone(String company) {
    
    
        return null;
    }

    @Override
    public Computer manufactureComputer(String company) {
    
    
        if ("Huawei".equalsIgnoreCase(company)) {
    
    
            return new HuaweiComputer();
        } else if ("Apple".equalsIgnoreCase(company)) {
    
    
            return new AppleComputer();
        }
        return null;
    }
}
/**
 * Phone工厂类
 *
 * @author dkangel
 */
public class PhoneFactory extends AbstractFactory {
    
    
    @Override
    public Phone manufacturePhone(String company) {
    
    
        if ("Huawei".equalsIgnoreCase(company)) {
    
    
            return new HuaweiPhone();
        } else if ("Apple".equalsIgnoreCase(company)) {
    
    
            return new ApplePhone();
        }
        return null;
    }

    @Override
    public Computer manufactureComputer(String company) {
    
    
        return null;
    }
}

7. 创建超级工厂类
/**
 * 超级工厂类,用于创建其具体的工厂类
 *
 * @author dkangel
 */
public class FactoryProducer {
    
    
    /**
     * 根据type获取具体的工厂
     *
     * @param type 工厂类型
     * @return AbstractFactory
     */
    public static AbstractFactory getFactory(String type) {
    
    
        if ("Phone".equalsIgnoreCase(type)) {
    
    
            return new PhoneFactory();
        } else if ("Computer".equalsIgnoreCase(type)) {
    
    
            return new ComputerFactory();
        }
        return null;
    }
}

8. 使用
/**
 * 抽象工厂使用类
 *
 * @author dkangel
 */
public class Main {
    
    
    public static void main(String[] args) {
    
    
        // 获取Phone工厂
        AbstractFactory phoneFactory = FactoryProducer.getFactory("phone");
        // 获取Huawei手机
        Phone phone = phoneFactory.manufacturePhone("Huawei");
        phone.call();
        // 获取Apple手机
        phone = phoneFactory.manufacturePhone("Apple");
        phone.call();

        AbstractFactory computerFactory = FactoryProducer.getFactory("computer");
        // 获取Huawei电脑
        Computer computer = computerFactory.manufactureComputer("Huawei");
        computer.code();
        // 获取Apple电脑
        computer = computerFactory.manufactureComputer("Apple");
        computer.code();
    }
}

Guess you like

Origin blog.csdn.net/Dkangel/article/details/105723774