设计模式之工厂方法模式

发布时间:2023年12月24日

工厂方法模式

1.定义

工厂方法模式使用的频率非常高,在我们日常的开发中总能见到它的身影。其定义为:

Define an interface for creating an object,but let subclasses decide which class to instantiate.Factory Method lets a class defer instantiation to subclasses.(定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。)

2.特点

  1. 良好的封装性,代码结构清晰
  2. 工厂方法模式的扩展性非常优秀。在增加产品类的情况下,只要适当地修改具体的工厂类或扩展一个工厂类,就可以完成“拥抱变化”。

3.示例代码

public abstract class Product {
    public void method1(){}
    public abstract void method2();
}
public class ConcreteProduct1 extends Product {
    public void method2() {}
}
public class ConcreteProduct2 extends Product {
    public void method2() {}
}
public abstract class Creator {
    public abstract <T extends Product> createProduct(Class<T> clazz);
}
public class ConcreteCreator extends Creator {
    public <T extends Product> createProduct(Class<T> clazz) {
        Product product = null;
        try {
            product = (Product)Class.forName(clazz.getName()).newInstance();
        } catch(Exeception e) {
            
        }

        return (T)product;
    }
}

4.扩展

  1. 简单工厂模式

    public class ObjectFactory<T> {
        private final static Map<String, IDao<?>> DAO_MAP = Maps.newHashMap();
        private static final String DEFAULT_PROPERTIES_FILE_NAME = "beans.properties";
    
        static {
            // 加载配置文件
            Properties properties = new Properties();
            try {
                properties
                    .load(Thread.currentThread().getContextClassLoader().getResourceAsStream(DEFAULT_PROPERTIES_FILE_NAME));
                if (CollectionUtils.isEmpty(properties.keySet())) {
                    throw new RuntimeException("properties is empty");
                }
                for (Object key : properties.keySet()) {
                    Object o = properties.get(key.toString());
                    Class<?> clazz = Class.forName(o.toString());
                    DAO_MAP.put(key.toString(), (IDao<?>)clazz.newInstance());
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    
        public static IDao<?> getDaoByName(String name) {
            return DAO_MAP.getOrDefault(name, null);
        }
    }
    
    public class StudentDaoImpl implements IDao<Student> {
        @Override
        public boolean save(Student o) {
            System.out.println("StudentDaoImpl.save");
            System.out.println(o);
            return true;
        }
    
        @Override
        public int update(Student o) {
            System.out.println("StudentDaoImpl.update");
            return 0;
        }
    
        @Override
        public boolean delete(Student o) {
            System.out.println("StudentDaoImpl.delete");
            return false;
        }
    
        @Override
        public Student selectById(String id) {
            System.out.println("StudentDaoImpl.selectById");
            return null;
        }
    }
    public class TeacherDaoImpl implements IDao<Teacher> {
        @Override
        public boolean save(Teacher o) {
            System.out.println("TeacherDaoImpl.save");
            return false;
        }
    
        @Override
        public int update(Teacher o) {
            System.out.println("TeacherDaoImpl.update");
            return 0;
        }
    
        @Override
        public boolean delete(Teacher o) {
            System.out.println("TeacherDaoImpl.delete");
            return false;
        }
    
        @Override
        public Teacher selectById(String id) {
            System.out.println("TeacherDaoImpl.selectById");
            return null;
        }
    }
    

    bean.properties

    studentDao=com.yxxmg.gof.create.pattern.factory.impl.StudentDaoImpl
    teacherDao=com.yxxmg.gof.create.pattern.factory.impl.TeacherDaoImpl
    

5.示例代码地址

https://gitee.com/youxiaxiaomage/java-practices/tree/master/yxxmg-gof-sample/src/main/java/com/yxxmg/gof/create/pattern/abstractfactory

文章来源:https://blog.csdn.net/youxiaxiaomage/article/details/135179813
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。