设计模式-抽象工厂模式

  1. 定义
    抽象工厂模式提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类。

  2. 代码实例

    /**
     * 抽象工厂
     */
    interface AbstractRobotFactory {
        String getName();
        int getPrice();
    }
    
    /**
     * 具体工厂,使用不同的具体工厂来获取不同的产品属性
     */
    class SuperRobotFactory implements AbstractRobotFactory {
    
        @Override
        public String getName() {
            return "Spuer Robot";
        }
    
        @Override
        public int getPrice() {
            return 8848;
        }
    }
    
    /**
     * 产品家族抽象
     */
    abstract class Robot {
        private String name;
        private int price;
    
        protected Robot() {}
    
        public abstract void createRobot(AbstractRobotFactory robotFactory);
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getPrice() {
            return price;
        }
    
        public void setPrice(int price) {
            this.price = price;
        }
    
        @Override
        public String toString() {
            return "Robot{" + "name='" + name + '\'' + ", price=" + price + '}';
        }
    }
    
    /**
     * 具体产品,从抽象工厂获取产品属性
     */
    class SuperRobot extends Robot {
    
        @Override
        public void createRobot(AbstractRobotFactory robotFactory) {
            setName(robotFactory.getName());
            setPrice(robotFactory.getPrice());
        }
    
        // 测试
        public static void main(String[] args) {
            Robot robot = new SuperRobot();
            robot.createRobot(new SuperRobotFactory());
    
            System.out.println(robot.toString());
        }
    }
    
posted @ 2019-08-16 10:03  bosslv  阅读(121)  评论(0编辑  收藏  举报