美文网首页
创建型设计模式-工厂方法模式

创建型设计模式-工厂方法模式

作者: 微风细雨007 | 来源:发表于2019-01-14 14:39 被阅读13次

    使用场景

    在任何需要生成复杂对象的地方,都可以使用工厂方法模式。复杂对象更适合使用工厂模式,用new就可以完成创建的对象无需使用工厂模式。

    示例

    抽象产品:手机,具体产品:小米手机,苹果手机;

    抽象工厂:手机工厂,具体工厂:小米手机工厂,苹果手机工厂

    UML图

    工厂模式示例
    • 抽象产品:手机
    public interface Mobile {
        void call();
    }
    
    • 具体产品1:小米手机
    public class MiPhone implements Mobile {
        public void call() {
            System.out.println("欢迎使用小米手机");
        }
    }
    
    • 具体产品2:苹果手机
    public class ApplePhone implements Mobile {
        public void call() {
            System.out.println("欢迎使用苹果手机");
        }
    }
    
    • 抽象工厂:手机工厂
    public interface MobileFactory {
        Mobile produce();
    }
    
    • 具体工厂1:小米手机工厂
    public class MiFactory implements MobileFactory {
        public Mobile produce() {
            return new MiPhone();
        }
    }
    
    • 具体工厂2:苹果手机工厂
    public class AppleFactory implements MobileFactory {
        public Mobile produce() {
            return new ApplePhone();
        }
    }
    
    • 实现
    public class FactoryMethodMain {
        public static void main(String[] args) {
            MobileFactory factory = new AppleFactory();
            Mobile produce = factory.produce();
            produce.call();
    
            //创建工厂
            MobileFactory miFactory = new MiFactory();
            //生产产品手机
            Mobile miPhone = miFactory.produce();
            //打电话
            miPhone.call();
        }
    }
    

    缺点

    每次我们为工厂方法添加新的产品时就要编写一个新的产品类,同时还要引入抽象层,这必然会导致结构的复杂化

    相关文章

      网友评论

          本文标题:创建型设计模式-工厂方法模式

          本文链接:https://www.haomeiwen.com/subject/yjoddqtx.html