美文网首页
工厂模式

工厂模式

作者: Doter | 来源:发表于2018-08-20 22:12 被阅读0次

工厂模式

工厂模式,简要来说就是需要什么样的产品调用对应产品工厂类进行创建即可。

优点:

  1. 使用方便,只需要指定需要哪种产品,至于产品如何创建不用关注。
  2. 利于扩展,且可以屏蔽工厂的实现。

java代码实例:

  1. 抽象一个产品,约定一下每个产品现在有一个getName()方法,
public interface Product {
    public String getName();
}
  1. 实现产品A,B
public class ProductA implements Product {
    @Override
    public String getName() {
        return "this is product A";
    }
}
public class ProductB implements Product {
    @Override
    public String getName() {
        return "this is product B";
    }
}
  1. 抽象工厂
public interface ProductFactory {
    public Product createProduct();
}
  1. 实现工厂:
public class ProductAFactory implements ProductFactory{
    @Override
    public Product createProduct() {
        return new ProductA();
    }
}
public class ProductBFactory implements ProductFactory{
    @Override
    public Product createProduct() {
        return new ProductB();
    }
}
  1. 使用:
public class Main {
    public static void main(String[] args) {
        Product product = new ProductAFactory().createProduct();
        System.out.println(product.getName());
        product = new ProductBFactory().createProduct();
        System.out.println(product.getName());
    }
}

接下来我尽可能的用代码演示它的优缺点。

  1. 如果我现在要生产新ProductC,那么我需要增加一个ProductC的实现及其工厂
public class ProductC implements Product {
    @Override
    public String getName() {
        return "this is product C";
    }
}
public class ProductCFactory implements ProductFactory{
    @Override
    public Product createProduct() {
        return new ProductC();
    }
}
  1. 在需要的地方即可生产ProductC
public class Main {
    public static void main(String[] args) {
        product = new ProductCFactory().createProduct();
        System.out.println(product.getName());
    }
}

根据以上分析,增加功能时,我并没有修改原有的代码。
优点:

  1. 屏蔽工厂的实现
  2. 实现‘开-闭 原则’

相关文章

  • 常用设计模式

    设计模式 工厂模式 工厂模式思路上分:简单工厂模式,工厂模式, 抽象工厂模式// 抽象工厂模式可以代替工厂模式,做...

  • 工厂模式

    工厂模式细分三种:简单工厂模式、工厂模式、抽象工厂模式。 工厂模式相当于抽象了简单工厂模式的工厂类,而抽象工厂模式...

  • 工厂模式

    工厂模式 就是工厂---生产-->产品 在设计模式中,分为 简单工厂模式, 工厂方法模式,抽象工厂模式. 工厂模式...

  • 找女朋友之简单工厂模式,工厂模式,抽象工厂模式

    找女朋友之简单工厂模式,工厂模式,抽象工厂模式 找女朋友之简单工厂模式,工厂模式,抽象工厂模式

  • 【设计模式】- 工厂模式

    工厂模式分为三种:简单工厂模式、工厂方法模式和抽象工厂模式。 工厂模式:靠工厂生产对象 简单工厂模式中只有一个工厂...

  • 工厂模式

    工厂模式包含三种模式:简单工厂模式、工厂方法模式和抽象工厂模式。 简单工厂模式 定义简单工厂模式:由一个工厂类根据...

  • Java设计模式——工厂模式

    工厂模式简单工厂模式工厂方法模式抽象工厂模式 1.简单工厂模式 1.基本介绍1)简单工厂模式也叫静态工厂模式,是属...

  • 设计模式-3种工厂模式

    工厂模式包括:简单工厂模式,工厂方法模式,抽象工厂模式 简单工厂模式 工厂方法根据参数直接创建实例:工厂->产品 ...

  • 设计模式-工厂模式

    工厂模式概念 实例化对象,用工厂方法代替new操作。工厂模式包括工厂方法模式和抽象工厂模式。抽象工厂模式是工厂模式...

  • 第一章2.0工厂- 基础类准备

    2.1工厂-简单工厂模式2.2工厂-工厂方法模式2.3工厂-抽象工厂模式

网友评论

      本文标题:工厂模式

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