• 工厂设计模式


    2. 工厂设计模式

    工厂模式分为三种更加细分的类型:简单工厂、工厂方法和抽象工厂。

    2.1 如何实现工厂模式

    2.1.1 简单工厂(Simple Factory)

    简单工厂叫作静态工厂方法模式(Static Factory Method Pattern)。

    现在有一个场景,需要一个资源加载器,根据不同的url进行资源加载,如果将所有的加载实现代码全部封装在了一个load方法中,就会导致一个类很大,同时扩展性也非常差,当要添加新的前缀解析其他类型的url时,发现需要修改大量的源代码,首先定义两个之后会用到的类:

    **
     * 类描述:资源类
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/14 20:41
     */
    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    public class Resource {
    
        private String url;
    }
    
    // 加载资源异常
    public class ResourceLoadException extends RuntimeException {
    
        public ResourceLoadException() {
            super("加载资源发生异常");
        }
    
        public ResourceLoadException(String message) {
            super(message);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    源码如下:

    /**
     * 类描述:加载资源的处理类
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/14 20:44
     */
    public class ResourceLoader {
    
        /**
         * 加载资源,获取资源对象
         *
         * @param url
         * @return
         */
        public Resource load(String url) {
            String prefix = getPrefix(url);
            if (Objects.equals("http", prefix)) {
                // 下载资源
                return new Resource(url);
            } else if (Objects.equals("file", prefix)) {
                // 文件流资源
                return new Resource(url);
            } else if (Objects.equals("classpath", prefix)) {
                // 类路径下的资源
                return new Resource(url);
            } else {
                return new Resource(("default"));
            }
        }
    
        /**
         * 获取资源路径的前缀
         *
         * @param url
         * @return
         */
        private String getPrefix(String url) {
            if (url == null || StringUtils.isEmpty(url) || !url.contains(":")) {
                throw new ResourceLoadException("此资源url不合法");
            }
            String[] split = url.split(":");
            return split[0];
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    上面案例中的ResourceLoader#load存在很多的if分支,如果分支数量不多且不需要扩展,这样的编写方式可以接受。在实际的工作场景中,我们的业务代码可能会很多,分支逻辑也可能十分复杂,这个时候简单工厂设计模式就要发挥作用了。

    不管有多少个分支逻辑,他的本质就是需要创造一个资源产品,我们只需要创建一个工厂类,将创建资源的能力交给工厂即可:

    /**
     * 类描述:资源工厂
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/14 20:51
     */
    public class ResourceFactory {
    	// 使用简单工厂模式(静态工厂方法模式),创建资源对象
        public static Resource create(String prefix, String url) {
            if (Objects.equals("http", prefix)) {
                // 下载资源
                return new Resource(url);
            } else if (Objects.equals("file", prefix)) {
                // 文件流资源
                return new Resource(url);
            } else if (Objects.equals("classpath", prefix)) {
                // 类路径下的资源
                return new Resource(url);
            } else {
                return new Resource(("default"));
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    我们将【创建资源产品】这个单一的能力赋予上面的产品工厂,这样能更好的符合单一原则。有了简单工厂之后,加载资源ResourceLoader#load的逻辑可以这样简化:

    /**
     * 类描述:加载资源的处理类
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/14 20:44
     */
    public class ResourceLoader {
    
        /**
         * 优化,使用简单工厂模式的资源工厂类{@link ResourceFactory#create(String, String)}来创建资源对象
         *
         * @param url
         * @return
         */
        public Resource load(String url) {
            String prefix = getPrefix(url);
            // 根据前缀处理不同的资源
            return ResourceFactory.create(prefix, url);
        }
    
        /**
         * 获取资源路径的前缀
         *
         * @param url
         * @return
         */
        private String getPrefix(String url) {
            if (url == null || StringUtils.isEmpty(url) || !url.contains(":")) {
                throw new ResourceLoadException("此资源url不合法");
            }
            String[] split = url.split(":");
            return split[0];
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    上面的案例过程就是简单工厂设计模式的应用,通过提取一个简单工厂类,将创建对象的过程交给简单工厂类、其他业务需要某个产品时,直接使用create方法根据传入的不同的类型创建不同的产品即可;

    这样的好处是:

    • 简单工厂将创建的过程进行封装,不需要关心创建的细节,更加符合面向对象思想
    • 主要的业务逻辑不会被创建对象的代码干扰,代码更易阅读
    • 产品的创建可以独立测试,将更容易测试
    • 独立的工厂类只负责创建产品,更加符合单一原则

    2.1.2 工厂方法(Factory Method)

    如果有一天,我们的if分支逻辑不断膨胀,就有必要将 if 分支逻辑去掉,那又该怎么办呢?

    比较经典的处理方法就是按照多态的实现思路,对上面的代码进行重构。我们会为每一个 Resource 创建一个独立的工厂类,将每一个实例的创建过程交给工厂类完成;

    之前是一个大而全的工厂,一个工厂需要创建不同的产品,工厂方法讲究的是工厂要专而精,一个工厂只创建一种资源(产品),奔驰工厂只负责生产奔驰,宝马工厂只负责生产宝马。

    回到我们的例子中,每一种url加载成不同的资源产品,那每一种资源都可以由一个独立的ResourceLoaderFactory生产,为了实现这一种场景,我们需要将生产资源的工厂类进行抽象:

    /**
     * 接口描述:抽象工厂,资源加载的抽象
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/14 22:12
     */
    public interface IResourceLoaderFactory {
        Resource load(String url);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    并为每一种资源创建与之匹配的具体实现(资源工厂):

    public class ClassPathResourceLoaderFactory implements IResourceLoaderFactory {
        @Override
        public Resource load(String url) {
            // 中间省略复杂的创建过程
            return new Resource(url);
        }
    }
    
    public class DefaultResourceLoaderFactory implements IResourceLoaderFactory {
        @Override
        public Resource load(String url) {
            // 中间省略复杂的创建过程
            return new Resource(url);
        }
    }
    
    public class FileResourceLoaderFactory implements IResourceLoaderFactory {
        @Override
        public Resource load(String url) {
            // 中间省略复杂的创建过程
            return new Resource(url);
        }
    }
    
    public class HttpResourceLoaderFactory implements IResourceLoaderFactory {
        @Override
        public Resource load(String url) {
            // 中间省略复杂的创建过程
            return new Resource(url);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    这就是工厂方法模式的典型代码实现。当需要新增一种读取资源的方式时,只需要新增一个工厂实现,并实现 IResourceLoaderFactory 接口即可。可见,工厂方法模式比起简单工厂模式更加符合开闭原则。

    使用资源工厂的代码就变成如下:

    /**
     * 类描述:加载资源类
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/14 22:20
     */
    public class ResourceLoader {
    
        /**
         * V1,加载资源,获取资源对象
         *
         * @param url
         * @return
         */
        public Resource load(String url) {
            String prefix = getPrefix(url);
            IResourceLoaderFactory resourceLoaderFactory = null;
            if (Objects.equals("http", prefix)) {
                // 下载资源
                resourceLoaderFactory = new HttpResourceLoaderFactory();
            } else if (Objects.equals("file", prefix)) {
                // 文件流资源
                resourceLoaderFactory = new FileResourceLoaderFactory();
            } else if (Objects.equals("classpath", prefix)) {
                // 类路径下的资源
                resourceLoaderFactory = new ClassPathResourceLoaderFactory();
            } else {
                resourceLoaderFactory = new DefaultResourceLoaderFactory();
            }
    
            return resourceLoaderFactory.load(url);
        }
    
        /**
         * 获取资源路径的前缀
         *
         * @param url
         * @return
         */
        private String getPrefix(String url) {
            if (url == null || StringUtils.isEmpty(url) || !url.contains(":")) {
                throw new ResourceLoadException("此资源url不合法");
            }
            String[] split = url.split(":");
            if (split.length > 1) {
                return split[0];
            } else {
                return "classpath";
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52

    ResourceLoader#load中还是存在if判断,当需要新增读取资源的场景时仍然要增加if判断,仍然不符合开闭原则。 为了解决上述的问题我们可以创建一个缓存来统一管理工厂实例,以后使用工厂就会更加的简单,代码如下:

    /**
     * 类描述:加载资源类
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/14 22:20
     */
    public class ResourceLoader {
        // V2, 使用缓存管理工厂实例
        private static Map<String, IResourceLoaderFactory> resourceLoaderFactoryCacheV2 = new HashMap<>();
    
        static {
            resourceLoaderFactoryCacheV2.put("http", new HttpResourceLoaderFactory());
            resourceLoaderFactoryCacheV2.put("file", new FileResourceLoaderFactory());
            resourceLoaderFactoryCacheV2.put("classpath", new ClassPathResourceLoaderFactory());
            resourceLoaderFactoryCacheV2.put("default", new DefaultResourceLoaderFactory());
        }
    
        /**
         * V2,加载资源,获取资源对象。 新增场景不再需要if判断了
         *
         * @param url
         * @return
         */
        public Resource load2(String url) {
            String prefix = getPrefix(url);
            return resourceLoaderFactoryCacheV2.get(prefix).load(url);
        }
    
        /**
         * 获取资源路径的前缀
         *
         * @param url
         * @return
         */
        private String getPrefix(String url) {
            if (url == null || StringUtils.isEmpty(url) || !url.contains(":")) {
                throw new ResourceLoadException("此资源url不合法");
            }
            String[] split = url.split(":");
            if (split.length > 1) {
                return split[0];
            } else {
                return "classpath";
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47

    新增场景,版本V2仍然需要修改static中的代码,可以写一个配置文件resourceLoader.properties,将工厂类进行配置:

    http=cn.itcast.designPatterns.factoryMethod.resourceFactory.HttpResourceLoaderFactory
    file=cn.itcast.designPatterns.factoryMethod.resourceFactory.FileResourceLoaderFactory
    classpath=cn.itcast.designPatterns.factoryMethod.resourceFactory.ClassPathResourceLoaderFactory
    default=cn.itcast.designPatterns.factoryMethod.resourceFactory.DefaultResourceLoaderFactory
    
    • 1
    • 2
    • 3
    • 4

    static中的缓存加载优化后完全满足开闭原则,代码如下:

    /**
     * 类描述:加载资源类
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/14 22:20
     */
    public class ResourceLoader {
        // V3
        private static Map<String, IResourceLoaderFactory> resourceLoaderFactoryCacheV3 = new HashMap<>();
    
        static {
    
            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("resourceLoader.properties");
            Properties properties = new Properties();
            try {
                properties.load(inputStream);
                for (Map.Entry<Object, Object> entry : properties.entrySet()) {
                    String key = entry.getKey().toString();
                    Class clazz = Class.forName(entry.getValue().toString());
                    IResourceLoaderFactory resourceLoaderFactory = (IResourceLoaderFactory) clazz.getConstructor().newInstance();
                    resourceLoaderFactoryCacheV3.put(key, resourceLoaderFactory);
                }
            } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException |
                     NoSuchMethodException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
    
        }
    
        /**
         * V3,加载资源,获取资源对象。新增场景不再需要if判断了
         *
         * @param url
         * @return
         */
        public Resource load3(String url) {
            String prefix = getPrefix(url);
            return resourceLoaderFactoryCacheV3.get(prefix).load(url);
        }
    
        /**
         * 获取资源路径的前缀
         *
         * @param url
         * @return
         */
        private String getPrefix(String url) {
            if (url == null || StringUtils.isEmpty(url) || !url.contains(":")) {
                throw new ResourceLoadException("此资源url不合法");
            }
            String[] split = url.split(":");
            if (split.length > 1) {
                return split[0];
            } else {
                return "classpath";
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59

    以后我们想新增或删除一个资源工厂只需要写一个类实现IResourceLoaderFactory接口,并在配置文件中进行配置即可。如此就完全看不到if-else的影子了。

    上面的代码中产品是简单单一的Resource类,在实际工作中,我们的产品可能是及其复杂的,我们同样需要对整个产品线进行抽象。将Resource进行抽象:

    /**
     * 类描述:资源(产品)的抽象
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/15 22:32
     */
    public abstract class AbstractResource {
        private String url;
    
        public AbstractResource() {
        }
    
        public AbstractResource(String url) {
            this.url = url;
        }
    
        protected void shared() {
            System.out.println("这是共享方法");
        }
    
        /**
         * 每个子类需要独自实现的方法
         *
         * @return 字节流
         */
        public abstract InputStream getInputStream();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    具体的产品需要继承这个抽象类:

    /**
     * 类描述:classpath资源(产品)
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/15 22:35
     */
    public class ClassPathResource extends AbstractResource {
    
        public ClassPathResource() {
        }
    
        public ClassPathResource(String url) {
            super(url);
        }
    
        @Override
        public InputStream getInputStream() {
            return null;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    其他产品同理,我们的工厂类也需要面向产品的抽象进行编程:

    /**
     * 类描述:classpath资源工厂
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/14 22:15
     */
    public class ClassPathResourceLoaderFactory2 implements IResourceLoaderFactory2 {
        @Override
        public AbstractResource load(String url) {
            // 中间省略复杂的创建过程
            return new ClassPathResource(url);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    resourceLoader2.properties配置工厂类:

    http=cn.itcast.designPatterns.factoryMethod.resourceFactory.HttpResourceLoaderFactory2
    file=cn.itcast.designPatterns.factoryMethod.resourceFactory.FileResourceLoaderFactory2
    classpath=cn.itcast.designPatterns.factoryMethod.resourceFactory.ClassPathResourceLoaderFactory2
    default=cn.itcast.designPatterns.factoryMethod.resourceFactory.DefaultResourceLoaderFactory2
    
    • 1
    • 2
    • 3
    • 4

    加载资源工厂:

    /**
     * 类描述:加载资源类
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/14 22:20
     */
    public class ResourceLoader {
        // V4
        private static Map<String, IResourceLoaderFactory2> resourceLoaderFactoryCacheV4 = new HashMap<>();
    
        static {
    
            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("resourceLoader2.properties");
            Properties properties = new Properties();
            try {
                properties.load(inputStream);
                for (Map.Entry<Object, Object> entry : properties.entrySet()) {
                    String key = entry.getKey().toString();
                    Class clazz = Class.forName(entry.getValue().toString());
                    IResourceLoaderFactory2 resourceLoaderFactory2 = (IResourceLoaderFactory2) clazz.getConstructor().newInstance();
                    resourceLoaderFactoryCacheV4.put(key, resourceLoaderFactory2);
                }
            } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException |
                     NoSuchMethodException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
    
        }
    
        /**
         * V4,加载资源,获取资源对象。抽象资源(产品)
         *
         * @param url
         * @return
         */
        public AbstractResource load4(String url) {
            return resourceLoaderFactoryCacheV4.get(getPrefix(url)).load(url);
        }
    
        /**
         * 获取资源路径的前缀
         *
         * @param url
         * @return
         */
        private String getPrefix(String url) {
            if (url == null || StringUtils.isEmpty(url) || !url.contains(":")) {
                throw new ResourceLoadException("此资源url不合法");
            }
            String[] split = url.split(":");
            if (split.length > 1) {
                return split[0];
            } else {
                return "classpath";
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58

    我们编写测试用例进行测试:

    /**
     * 类描述:设计模式的测试用例
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/6 22:43
     */
    @Slf4j
    public class DesignPatternTest {
        @Test
        public void testFactoryMethod() {
            String url = "file://D://a.txt";
            // 测试简单工厂
            ResourceLoader resourceLoader = new cn.itcast.designPatterns.simpleFactory.ResourceLoader();
            Resource resource = resourceLoader.load(url);
            log.info("resource --> {}", resource.getClass().getName());
    
            // 测试工厂方法
            cn.itcast.designPatterns.factoryMethod.ResourceLoader resourceLoader1 = new cn.itcast.designPatterns.factoryMethod.ResourceLoader();
            Resource resource1 = resourceLoader1.load3(url);
            log.info("resource --> {}", resource.getClass().getName());
    
            // 测试工厂方法,抽象资源(产品)
            String url2 = "classpath:resourceLoader2.properties";
            AbstractResource abstractResource = resourceLoader1.load4(url2);
            log.info("resource --> {}", abstractResource.getClass().getName());
    
            // 解决此处SLF4J的打日志的问题:https://www.cnblogs.com/fangjb/p/12964710.html
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    测试结果:

    [main] INFO cn.itcast.designPattern.DesignPatternTest - resource --> cn.itcast.designPatterns.simpleFactory.Resource
    [main] INFO cn.itcast.designPattern.DesignPatternTest - resource --> cn.itcast.designPatterns.simpleFactory.Resource
    [main] INFO cn.itcast.designPattern.DesignPatternTest - resource --> cn.itcast.designPatterns.factoryMethod.product.ClassPathResource
    
    • 1
    • 2
    • 3

    2.1.3 抽象工厂(Abstract Factory)

    为创建一组相关或者相互依赖的对象提供一个接口,而且无须指定他们的具体类。

    抽象工厂模式是工厂方法模式的升级版本,在有多个业务品种、业务分类时,通过抽象工厂模式生产需要的对象。

    在简单工厂和工厂方法中,往往只需要创建一种类型的产品,但是如果需求改变,需要增加多种类型的产品,即增加产品族,假设需求是创建各种类型的资源,我们在上面案例的基础上再增加一个维度,如图片资源、视频资源、文本资源等。

    为了管理产品族,将资源(产品)进行抽象, 抽象出picture,text,video产品的抽象资源类,都实现Resource接口。

    /**
     * 接口描述:资源(产品)抽象接口
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 21:55
     */
    public interface Resource {
    
        /**
         * 读取资源,返回流对象
         *
         * @param url
         * @return
         */
        InputStream getStream(String url);
    }
    
    /**
     * 类描述:picture资源(产品)的抽象,产品族
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 22:00
     */
    public class AbstractPictureResource implements Resource {
    
        // 图片的一些公用的成员变量,方法都可以定义在这个类中
    
        private String url;
    
        public AbstractPictureResource() {
        }
    
        public AbstractPictureResource(String url) {
            this.url = url;
        }
    
        @Override
        public InputStream getStream(String url) {
            try {
                return new FileInputStream(url);
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
    }
    
    public class AbstractTextResource implements Resource {
    
        // text文本的一些公用的成员变量,方法都可以定义在这个类中
    
        private String url;
    
        public AbstractTextResource() {
        }
    
        public AbstractTextResource(String url) {
            this.url = url;
        }
    
        @Override
        public InputStream getStream(String url) {
            try {
                return new FileInputStream(url);
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
    }
    
    public class AbstractVideoResource implements Resource {
    
        // 视频video的一些公用的成员变量,方法都可以定义在这个类中
    
        private String url;
    
        public AbstractVideoResource() {
        }
    
        public AbstractVideoResource(String url) {
            this.url = url;
        }
    
        @Override
        public InputStream getStream(String url) {
            try {
                return new FileInputStream(url);
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93

    再来看看抽象资源(产品)的具体实现, 根据不同类型编写对于的具体实现:

    /**
     * 类描述:classpath图片资源
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 22:11
     */
    @Slf4j
    public class ClassPathPictureResource extends AbstractPictureResource {
    
        public ClassPathPictureResource() {
        }
    
        public ClassPathPictureResource(String url) {
            super(url);
        }
    
        @Override
        public InputStream getStream(String url) {
            log.info(">>>{}, url: {}", this.getClass().getSimpleName(), url);
            return super.getStream(url);
        }
    }
    
    /**
     * 类描述:classpath文本资源
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 22:34
     */
    @Slf4j
    public class ClassPathTextResource extends AbstractTextResource {
    
        public ClassPathTextResource() {
        }
    
        public ClassPathTextResource(String url) {
            super(url);
        }
    
        @Override
        public InputStream getStream(String url) {
            log.info(">>>{}, url: {}", this.getClass().getSimpleName(), url);
            return super.getStream(url);
        }
    }
    
    /**
     * 类描述:classpath视频资源
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 22:32
     */
    @Slf4j
    public class ClassPathVideoResource extends AbstractVideoResource {
    
        public ClassPathVideoResource() {
        }
    
        public ClassPathVideoResource(String url) {
            super(url);
        }
    
        @Override
        public InputStream getStream(String url) {
            log.info(">>>{}, url: {}", this.getClass().getSimpleName(), url);
            return super.getStream(url);
        }
    }
    
    /**
     * 类描述:默认图片资源
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 22:11
     */
    @Slf4j
    public class DefaultPictureResource extends AbstractPictureResource {
    
        public DefaultPictureResource() {
        }
    
        public DefaultPictureResource(String url) {
            super(url);
        }
    
        @Override
        public InputStream getStream(String url) {
            log.info(">>>{}, url: {}", this.getClass().getSimpleName(), url);
            return super.getStream(url);
        }
    }
    /**
     * 类描述:默认文本资源
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 22:34
     */
    @Slf4j
    public class DefaultTextResource extends AbstractTextResource {
    
        public DefaultTextResource() {
        }
    
        public DefaultTextResource(String url) {
            super(url);
        }
    
        @Override
        public InputStream getStream(String url) {
            log.info(">>>{}, url: {}", this.getClass().getSimpleName(), url);
            return super.getStream(url);
        }
    }
    
    /**
     * 类描述:默认视频资源
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 22:32
     */
    @Slf4j
    public class DefaultVideoResource extends AbstractVideoResource {
    
        public DefaultVideoResource() {
        }
    
        public DefaultVideoResource(String url) {
            super(url);
        }
    
        @Override
        public InputStream getStream(String url) {
    
            return super.getStream(url);
        }
    }
    /**
     * 类描述:file图片资源
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 22:11
     */
    @Slf4j
    public class FilePictureResource extends AbstractPictureResource {
    
        public FilePictureResource() {
        }
    
        public FilePictureResource(String url) {
            super(url);
        }
    
        @Override
        public InputStream getStream(String url) {
            log.info(">>>{}, url: {}", this.getClass().getSimpleName(), url);
            return super.getStream(url);
        }
    }
    /**
     * 类描述:file文本资源
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 22:34
     */
    @Slf4j
    public class FileTextResource extends AbstractTextResource {
    
        public FileTextResource() {
        }
    
        public FileTextResource(String url) {
            super(url);
        }
    
        @Override
        public InputStream getStream(String url) {
            log.info(">>>{}, url: {}", this.getClass().getSimpleName(), url);
            return super.getStream(url);
        }
    }
    /**
     * 类描述:file视频资源
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 22:32
     */
    @Slf4j
    public class FileVideoResource extends AbstractVideoResource {
    
        public FileVideoResource() {
        }
    
        public FileVideoResource(String url) {
            super(url);
        }
    
        @Override
        public InputStream getStream(String url) {
            log.info(">>>{}, url: {}", this.getClass().getSimpleName(), url);
            return super.getStream(url);
        }
    }
    
    /**
     * 类描述:http图片资源
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 22:11
     */
    @Slf4j
    public class HttpPictureResource extends AbstractPictureResource {
    
        public HttpPictureResource() {
        }
    
        public HttpPictureResource(String url) {
            super(url);
        }
    
        @Override
        public InputStream getStream(String url) {
            log.info(">>>{}, url: {}", this.getClass().getSimpleName(), url);
            return super.getStream(url);
        }
    }
    
    /**
     * 类描述:http文本资源
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 22:34
     */
    @Slf4j
    public class HttpTextResource extends AbstractTextResource {
    
        public HttpTextResource() {
        }
    
        public HttpTextResource(String url) {
            super(url);
        }
    
        @Override
        public InputStream getStream(String url) {
            log.info(">>>{}, url: {}", this.getClass().getSimpleName(), url);
            return super.getStream(url);
        }
    }
    
    /**
     * 类描述:http视频资源
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 22:32
     */
    @Slf4j
    public class HttpVideoResource extends AbstractVideoResource {
    
        public HttpVideoResource() {
        }
    
        public HttpVideoResource(String url) {
            super(url);
        }
    
        @Override
        public InputStream getStream(String url) {
            log.info(">>>{}, url: {}", this.getClass().getSimpleName(), url);
            return super.getStream(url);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283

    抽象资源工厂:

    /**
     * 接口描述:抽象工厂,每一个工厂实例都可以生产一个产品族
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/14 22:12
     */
    public interface IResourceLoaderFactory {
        /**
         * 加载图片资源的工厂方法
         *
         * @param url
         * @return
         */
        AbstractPictureResource loadPcitureResource(String url);
    
        /**
         * 加载视频资源的工厂方法
         *
         * @param url
         * @return
         */
        AbstractVideoResource loadVideoResource(String url);
    
        /**
         * 加载文本资源的工厂方法
         *
         * @param url
         * @return
         */
        AbstractTextResource loadTextResource(String url);
    }
    
    /**
     * 类描述:抽象的工厂
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 22:23
     */
    public abstract class AbstractResourceLoaderFactory implements IResourceLoaderFactory {
    
        // 可以提供共享的方法、模板、共享的变量资源等
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    根据不同的url类型编写具体的资源工厂实现:

    /**
     * 类描述:classpath资源工厂的实现
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 22:16
     */
    public class ClasspathResourceLoaderFactory extends AbstractResourceLoaderFactory {
        @Override
        public AbstractPictureResource loadPcitureResource(String url) {
            return new ClassPathPictureResource(url);
        }
    
        @Override
        public AbstractVideoResource loadVideoResource(String url) {
            return new ClassPathVideoResource(url);
        }
    
        @Override
        public AbstractTextResource loadTextResource(String url) {
            return new ClassPathTextResource(url);
        }
    }
    
    /**
     * 类描述:default默认资源工厂的实现
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 22:16
     */
    public class DefaultResourceLoaderFactory extends AbstractResourceLoaderFactory {
        @Override
        public AbstractPictureResource loadPcitureResource(String url) {
            return new DefaultPictureResource(url);
        }
    
        @Override
        public AbstractVideoResource loadVideoResource(String url) {
            return new DefaultVideoResource(url);
        }
    
        @Override
        public AbstractTextResource loadTextResource(String url) {
            return new DefaultTextResource(url);
        }
    }
    
    /**
     * 类描述:file资源工厂的实现
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 22:16
     */
    public class FileResourceLoaderFactory extends AbstractResourceLoaderFactory {
        @Override
        public AbstractPictureResource loadPcitureResource(String url) {
            return new FilePictureResource(url);
        }
    
        @Override
        public AbstractVideoResource loadVideoResource(String url) {
            return new FileVideoResource(url);
        }
    
        @Override
        public AbstractTextResource loadTextResource(String url) {
            return new FileTextResource(url);
        }
    }
    
    /**
     * 类描述:http资源工厂的实现
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/16 22:16
     */
    public class HttpResourceLoaderFactory extends AbstractResourceLoaderFactory {
        @Override
        public AbstractPictureResource loadPcitureResource(String url) {
            return new HttpPictureResource(url);
        }
    
        @Override
        public AbstractVideoResource loadVideoResource(String url) {
            return new HttpVideoResource(url);
        }
    
        @Override
        public AbstractTextResource loadTextResource(String url) {
            return new HttpTextResource(url);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95

    resourceLoader3.properties

    http=cn.itcast.designPatterns.abstractFactory.resourceFactory.impl.HttpResourceLoaderFactory
    file=cn.itcast.designPatterns.abstractFactory.resourceFactory.impl.FileResourceLoaderFactory
    classpath=cn.itcast.designPatterns.abstractFactory.resourceFactory.impl.ClasspathResourceLoaderFactory
    default=cn.itcast.designPatterns.abstractFactory.resourceFactory.impl.DefaultResourceLoaderFactory
    
    • 1
    • 2
    • 3
    • 4

    使用资源工厂加载资源:

    /**
     * 类描述:加载资源类
     *
     * @Author crysw
     * @Version 1.0
     * @Date 2023/11/19 17:04
     */
    public class ResourceLoader {
    
        private static Map<String, IResourceLoaderFactory> resourceLoaderFactoryCache = new HashMap<>();
    
        static {
            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("resourceLoader3.properties");
            Properties properties = new Properties();
            try {
                properties.load(inputStream);
                for (Map.Entry<Object, Object> entry : properties.entrySet()) {
                    String key = (String) entry.getKey();
                    Class<?> clazz = Class.forName(entry.getValue().toString());
                    IResourceLoaderFactory resourceLoaderFactory = (IResourceLoaderFactory) clazz.getConstructor().newInstance();
                    resourceLoaderFactoryCache.put(key, resourceLoaderFactory);
                }
            } catch (IOException | ClassNotFoundException | NoSuchMethodException | InstantiationException |
                     IllegalAccessException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
    
        }
    
        /**
         * 加载picture资源
         *
         * @param url
         * @return
         */
        public AbstractPictureResource loadPictureResource(String url) {
            return resourceLoaderFactoryCache.get(getPrefix(url)).loadPcitureResource(getUrl(url));
        }
    
        /**
         * 加载视频资源
         *
         * @param url
         * @return
         */
        public AbstractVideoResource loadVideoResource(String url) {
            return resourceLoaderFactoryCache.get(getPrefix(url)).loadVideoResource(getUrl(url));
        }
    
        /**
         * 加载文本资源
         *
         * @param url
         * @return
         */
    
        public AbstractTextResource loadTextResource(String url) {
            return resourceLoaderFactoryCache.get(getPrefix(url)).loadTextResource(getUrl(url));
        }
    
        /**
         * 获取资源路径的前缀
         *
         * @param url
         * @return
         */
        private String getPrefix(String url) {
            if (url == null || StringUtils.isEmpty(url) || !url.contains(":")) {
                throw new ResourceLoadException("此资源url不合法");
            }
            String[] split = url.split(":");
            if (split.length > 1) {
                return split[0];
            } else {
                return "classpath";
            }
        }
    
        /**
         * 获取正确的url路径
         *
         * @param url
         * @return
         */
        public String getUrl(String url) {
            if (url == null || StringUtils.isEmpty(url) || !url.contains(":")) {
                throw new ResourceLoadException("此资源url不合法");
            }
    
            return url.substring(url.indexOf("://") + "://".length());
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93

    测试抽象工厂:

    @Test
    public void testAbstractFactory() {
    	String url = "file://D:/Personal/note.txt";
    	cn.itcast.designPatterns.abstractFactory.resourceFactory.ResourceLoader resourceLoader = new cn.itcast.designPatterns.abstractFactory.resourceFactory.ResourceLoader();
    	log.info(">>>{}", resourceLoader.loadPictureResource(url).getStream(resourceLoader.getUrl(url)));
    	log.info(">>>{}", resourceLoader.loadVideoResource(url).getStream(resourceLoader.getUrl(url)));
    	log.info(">>>{}", resourceLoader.loadTextResource(url).getStream(resourceLoader.getUrl(url)));
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    测试结果:

    [main] INFO cn.itcast.designPatterns.abstractFactory.product.impl.FilePictureResource - >>>FilePictureResource, url: D:/Personal/note.txt
    [main] INFO cn.itcast.designPattern.DesignPatternTest - >>>java.io.FileInputStream@1f554b06
    [main] INFO cn.itcast.designPatterns.abstractFactory.product.impl.FileVideoResource - >>>FileVideoResource, url: D:/Personal/note.txt
    [main] INFO cn.itcast.designPattern.DesignPatternTest - >>>java.io.FileInputStream@131276c2
    [main] INFO cn.itcast.designPatterns.abstractFactory.product.impl.FileTextResource - >>>FileTextResource, url: D:/Personal/note.txt
    [main] INFO cn.itcast.designPattern.DesignPatternTest - >>>java.io.FileInputStream@711f39f9
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2.2 源码应用

    //todo

  • 相关阅读:
    求数组最大连续子数组乘积(轮询)
    【RHCE】作业:DNS主从同步&防火墙iptables服务使用
    0. HarmonyOS开发环境搭建问题
    7个理由让你的组织爱上OKR
    AXI-Stream协议详解(3)—— AXI4-Stream IP核原理分析
    定额人工费调整差额的几个解决方案
    SpringBoot数据响应、分层解耦、三层架构
    罗素《为什么我不是基督徒》的后果
    python蒙特卡罗方法计算圆周率近似值和定积分
    Java锁对象
  • 原文地址:https://blog.csdn.net/u013044713/article/details/134497531