[Design pattern] Simple factory, factory method, abstract factory

Article Directory

Simple factory

  • Definition :由一个工厂对象决定创建出哪一种产品类的实例
  • Type : Creation type, but it does not belong to the 23 design patterns of GOF (Gang of Four)
  • Use scenario :
    • The factory class is responsible for creating fewer objects
    • The client (application layer) only knows the parameters passed into the factory class, and does not care about how to create the object logic
  • Advantages : only need to pass in a correct parameter, you can get the object you need without knowing the details of its creation
  • Disadvantages : The responsibilities of the factory category are relatively heavy. Adding new products requires modifying the judgment logic of the factory category, which violates the principle of opening and closing.
  • Coding
public abstract class Video {
    
    
    public abstract void produce();
}
/**
 * Java视频类
 */
public class JavaVideo extends Video {
    
    
    @Override
    public void produce() {
    
    
        System.out.println("Java。。。");
    }
}
/**
 * Python视频类
 */
public class PythonVideo extends Video {
    
    
    @Override
    public void produce() {
    
    
        System.out.println("Python。。。");
    }
}
/**
 * 生产实例工厂
 */
public class VideoFactory {
    
    
    public Video getVideo(String type){
    
    
        if("java".equalsIgnoreCase(type)){
    
    
            return new JavaVideo();
        }else if("python".equalsIgnoreCase(type)){
    
    
            return new PythonVideo();
        }
        return null;
    }
}
public class Test {
    
    
    public static void main(String[] args) {
    
    
        VideoFactory videoFactory = new VideoFactory();
        Video video = videoFactory.getVideo("java");
        if (video == null) {
    
    
            return;
        }
        video.produce();
    }
}
==================================== 控制台输出 =======================================
Java。。。
  • UML class diagram :
    Simple factory UML class diagram
  • Note : Looking at the UML diagram, it is very clear. The Test test class only creates a Video factory, while Java and Python are created by the factory, and Test can obtain Java or Python instances through the factory. The shortcomings are also obvious. If you come to another Go language class, you need to modify the factory, and modify each time you add one. This will bring risks and does not comply with the opening and closing principle.
  • Transformation of reflection method :
public class VideoFactory {
    
    
    public Video getVideo(Class c){
    
    
        Video video = null;
        try {
    
    
            video = (Video) Class.forName(c.getName()).newInstance();
        } catch (InstantiationException e) {
    
    
            e.printStackTrace();
        } catch (IllegalAccessException e) {
    
    
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        }
        return video;
    }
}
/**
 * 只需要传入需要生成类的Class类型,工厂会通过反射返回实例对象
 */
public class Test {
    
    
    public static void main(String[] args) {
    
    
        VideoFactory videoFactory = new VideoFactory();
        Video video = videoFactory.getVideo(JavaVideo.class);
        if(video == null){
    
    
            return;
        }
        video.produce();
    }
}
  • Example of use in JDK source code : java.util.Calendar#createCalendar
	Calendar cal = null;
	if (aLocale.hasExtensions()) {
    
    
	    String caltype = aLocale.getUnicodeLocaleType("ca");
	    if (caltype != null) {
    
    
	        switch (caltype) {
    
    
	        case "buddhist":
	        cal = new BuddhistCalendar(zone, aLocale);
	            break;
	        case "japanese":
	            cal = new JapaneseImperialCalendar(zone, aLocale);
	            break;
	        case "gregory":
	            cal = new GregorianCalendar(zone, aLocale);
	            break;
	        }
	    }
	}

Factory method

  • Definition : Define an interface for creating objects, and let the class that implements this interface decide which class to instantiate,工厂方法让类的实例化推迟到子类中进行
  • Type : Creation
  • Use scenario :
    • Creating objects requires a lot of repetitive code
    • The client (application layer) does not depend on the details of how the product class instance is created and implemented
    • A class specifies which object to create through its subclass class
  • Advantages :
    • The user only needs to care about the factory corresponding to the product, and does not need to care about the creation details
    • Adding new products conforms to the principle of opening and closing, improving scalability
  • Disadvantages :
    • The number of classes is easy to be too much, increasing complexity
    • Increased the abstraction and difficulty of understanding the system
  • Coding

public abstract class Video {
    
    
    public abstract void produce();
}
/**
 * 三个实例对象
 */
public class FEVideo extends Video{
    
    
    @Override
    public void produce() {
    
    
        System.out.println("FE。。。");
    }
}
public class JavaVideo extends Video {
    
    
    @Override
    public void produce() {
    
    
        System.out.println("Java。。。");
    }
}
public class PythonVideo extends Video {
    
    
    @Override
    public void produce() {
    
    
        System.out.println("Python。。。");
    }
}
/**
 * 只制定规范契约,并不决定产生哪一种类的实例,产生哪一种实例完全交由子类实现
 */
public abstract class VideoFactory {
    
    
    public abstract Video getVideo();
}
/**
 * 只制定规范契约,并不决定产生哪一种类的实例,产生哪一种实例完全交由子类实现
 */
public class PythonVideoFactory extends VideoFactory {
    
    
    @Override
    public Video getVideo() {
    
    
        return new PythonVideo();
    }
}
public class JavaVideoFactory extends VideoFactory {
    
    
    @Override
    public Video getVideo() {
    
    
        return new JavaVideo();
    }
}
public class FEVideoFactory extends VideoFactory{
    
    
    @Override
    public Video getVideo() {
    
    
        return new FEVideo();
    }
}
public class Test {
    
    
    public static void main(String[] args) {
    
    
        VideoFactory videoFactory = new PythonVideoFactory();
        VideoFactory videoFactory2 = new JavaVideoFactory();
        VideoFactory videoFactory3 = new FEVideoFactory();
        Video video = videoFactory.getVideo();
        video.produce();
    }
}
==================================== 控制台输出 =======================================
Java。。。
  • UML class diagram :
    Factory method UML class diagram
  • Note : You can see that the three instance factories correspond to the production of the instances of the three classes. Which instance should be used in the Test test class, just find the factory instance of the object to get.
  • Example of use in JDK source code : java.util.Collection#iterator, factory interface method

Abstract factory

  • Definition : The abstract factory pattern provides one 创建一系列相关或相互依赖对象的接口, no need to specify their specific class
  • Type : Creation
  • Use scenario :
    • The client (application layer) does not depend on the details of how the product class instance is created and implemented
    • Emphasizes that a series of related product objects (belonging to the same product family, the concept of product family is explained later) is used together to create objects that require a lot of repetitive code
    • Provide a product class library, all products appear with the same interface, so that the client does not depend on the specific implementation
  • Advantages :
    • Specific products are isolated in the application layer code, no need to care about the creation details
    • Unify a series of product families together to create
  • Disadvantages :
    • It specifies all the product sets that may be created. It is difficult to extend new products in the product family, and it is necessary to modify the interface of the abstract factory
    • Increased the abstraction and difficulty of understanding the system
  • Coding
/**
 * 定义文章抽象类和两个继承类
 */
public abstract class Article {
    
    
    public abstract void produce();
}
public class JavaArticle extends Article {
    
    
    @Override
    public void produce() {
    
    
        System.out.println("Java文章。。。");
    }
}
public class PythonArticle extends Article {
    
    
    @Override
    public void produce() {
    
    
        System.out.println("Python文章。。。");
    }
}
/**
 * 定义视频抽象类和两个继承类
 */
public abstract class Video {
    
    
    public abstract void produce();
}
public class JavaVideo extends Video {
    
    
    @Override
    public void produce() {
    
    
        System.out.println("Java。。。");
    }
}
public class PythonVideo extends Video {
    
    
    @Override
    public void produce() {
    
    
        System.out.println("Python。。。");
    }
}
/**
 * 
 */
public interface CourseFactory {
    
    
    Video getVideo();
    Article getArticle();
}
public class JavaCourseFactory implements CourseFactory {
    
    
    @Override
    public Video getVideo() {
    
    
        return new JavaVideo();
    }
    @Override
    public Article getArticle() {
    
    
        return new JavaArticle();
    }
}
public class PythonCourseFactory implements CourseFactory {
    
    
    @Override
    public Video getVideo() {
    
    
        return new PythonVideo();
    }
    @Override
    public Article getArticle() {
    
    
        return new PythonArticle();
    }
}
public class Test {
    
    
    public static void main(String[] args) {
    
    
        CourseFactory courseFactory = new JavaCourseFactory();
        Video video = courseFactory.getVideo();
        Article article = courseFactory.getArticle();
        video.produce();
        article.produce();
    }
}
==================================== 控制台输出 =======================================
Java视频。。。
Java文章。。。
  • UML class diagram :
    Abstract factory UML class diagram
  • Note : You can see that the three instance factories correspond to the production of the instances of the three classes. Which instance should be used in the Test test class, just find the factory instance of the object to get.
  • Example of use in JDK source code : java.util.Collection#iterator, factory interface method

What is product family

  • Icon :
    Product family icon
  • Description :
    • Each row is a product family, such as Midea, a square represents a beautiful refrigerator, a circle represents a beautiful air conditioner, and an oval represents a beautiful water heater.
    • Each column is a product level structure. For example, the circle in the first row represents Midea air conditioners, the circle in the second row represents Gree air conditioners, and the circle in the third row represents Haier air conditioners.

Guess you like

Origin blog.csdn.net/qq_36221788/article/details/114444299