设计模式之工厂模式

设计模式之工厂模式

1.工厂模式的概念

实例化对象,用工厂方法代替new操作,工厂模式包括工厂方法模式和抽象工厂模式.抽象工厂模式的工厂方法模式的扩展

2.工厂模式的意图

定义一个接口来创建对象,但是让子类来决定那些类需要被实例化,工厂方法将实例化的工作推迟到子类中去实现.

3.工厂模式的应用场景

有一组类似的对象需要创建,在编码时不能预见需要创建哪种类的实例.系统需要考虑扩展性,不依赖于产品类实例如何被创建,组合和表达的细节.

4.工厂模式的设计思想

在软件系统中经常面临着对象的创建同工作,由于需求的变化,这个对象可能也随之发生变化,但它却拥有比较稳定的接口.为此,我们需要提供一种封装机制来隔离出这个异变对象的变化,从而保持系统中其他依赖该对象的对象不随着需求变化而变化.

5.工厂模式的好处

尽量松耦合,一个对象的依赖对象的变化与本身无关.
具体产品与客户端剥离,责任分割.

在这里插入图片描述在这里插入图片描述

代码 简单工厂模式

1.先创建颜色接口 ColorInterface

/**
 * 颜色接口
 */
public interface ColorInterface {
    public void color();
}

2.不同的颜色类实现颜色接口
Blue

public class Blue implements ColorInterface {
    public void color() {
        System.out.println("蓝色");
    }
}

Green

public class Green implements ColorInterface {
    public void color() {
        System.out.println("绿色");
    }
}

Red

public class Red implements ColorInterface {
    public void color() {
        System.out.println("红色");
    }
}

测试

public class ColorTest {
    public static void main(String[] args) {
        ColorInterface blue =  new Blue();
        blue.color();
        ColorInterface red = new Red();
        red.color();
        ColorInterface green = new Green();
        green.color();
    }
}

结果
在这里插入图片描述

这样写很麻烦,现在需要一个颜色工厂来帮我们创建颜色的实例

创建颜色工厂

/**
 * 颜色工厂
 */
public class ColorFactory {
    public ColorInterface getColor(String type){
        if ("blue".equals(type)){
            return new Blue();
        }else if ("red".equals(type)){
            return new Red();
        }else if ("green".equals(type)){
            return new Green();
        }
        return null;
    }
}

测试

public class ColorTest {
    public static void main(String[] args) {
        ColorFactory colorFactory = new ColorFactory();
        colorFactory.getColor("blue").color();
        colorFactory.getColor("red").color();
        colorFactory.getColor("green").color();
    }
}

结果
在这里插入图片描述

这样写工厂类就不灵活也不利于扩展,继续改进,利用反射来创建实例

颜色工厂类修改

/**
 * 颜色工厂
 */
public class ColorFactory {
    /**
     * 根据类名称来生产对象
     * @param className
     * @return
     */
    public ColorInterface getColor(String className){
        try {
            ColorInterface color = (ColorInterface) Class.forName(className).newInstance();
            return color;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}

测试

public class ColorTest {
    public static void main(String[] args) {
        ColorFactory colorFactory = new ColorFactory();
       colorFactory.getColor("com.spring.factory.Blue").color();
       colorFactory.getColor("com.spring.factory.Red").color();
       colorFactory.getColor("com.spring.factory.Green").color();
    }
}

结果
在这里插入图片描述

还可以将全限定名写入配置文件,通过配置文件中的key来实例化

在resource路径下新建type.pproperties配置文件

blue=com.spring.factory.Blue
red=com.spring.factory.Red
green=com.spring.factory.Green

新建PropertiesReader来读取配置文件

/**
 * 读取properties文件
 */
public class PropertiesReder {
    public Map<String,String> getProperties(){
        Properties properties = new Properties();
        Map<String,String> map = new HashMap<String, String>();
        try {
            InputStream in = getClass().getResourceAsStream("/type.properties");
            properties.load(in);
            Enumeration<?> enumeration = properties.propertyNames();
            while (enumeration.hasMoreElements()){
                String key = (String) enumeration.nextElement();
                String property = properties.getProperty(key);
                map.put(key,property);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
}

改写ColorFactory

/**
 * 读取properties文件
 */
public class PropertiesReder {
    public Map<String,String> getProperties(){
        Properties properties = new Properties();
        Map<String,String> map = new HashMap<String, String>();
        try {
            InputStream in = getClass().getResourceAsStream("/type.properties");
            properties.load(in);
            Enumeration<?> enumeration = properties.propertyNames();
            while (enumeration.hasMoreElements()){
                String key = (String) enumeration.nextElement();
                String property = properties.getProperty(key);
                map.put(key,property);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
}

测试

public class ColorTest {
    public static void main(String[] args) {
        ColorFactory colorFactory = new ColorFactory();
       colorFactory.getColor("blue").color();
       colorFactory.getColor("red").color();
       colorFactory.getColor("green").color();
    }
}

结果

在这里插入图片描述

抽象工厂模式

抽象工厂模式是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。

代码

钢笔接口

/**
 * 钢笔
 */
public interface Pen {
    public void write();
}

橡皮接口

/**
 * 橡皮
 */
public interface Eraser {
    public void raclage();
}

红色钢笔

/**
 * 红色钢笔
 */
public class RedPen implements Pen {
    public void write() {
        System.out.println("红色钢笔");
    }
}

蓝色钢笔

/**
 * 蓝色钢笔
 */
public class BluePen implements Pen {
    public void write() {
        System.out.println("蓝色钢笔");
    }
}

红色橡皮

/**
 * 红色橡皮
 */
public class RedEraser implements Eraser {
    public void raclage() {
        System.out.println("红色橡皮");
    }
}

蓝色橡皮

/**
 * 蓝色橡皮
 */
public class BlueEraser implements Eraser {
    public void raclage() {
        System.out.println("蓝色橡皮");
    }
}

文具工厂

/**
 * 文具工厂
 */
public interface StationeryFactory {
    public Pen getPen();
    public Eraser getEraser();
}

蓝色工厂

/**
 * 蓝色工厂
 */
public class BlueFactory implements StationeryFactory {
    public Pen getPen() {
        return new BluePen();
    }

    public Eraser getEraser() {
        return new BlueEraser();
    }
}

红色工厂

/**
 * 红色工厂
 */
public class RedFactory implements StationeryFactory {
    public Pen getPen() {
        return new RedPen();
    }

    public Eraser getEraser() {
        return new RedEraser();
    }
}

测试

public class Test {
    public static void main(String[] args) {
        StationeryFactory factory = new RedFactory();
        factory.getEraser().raclage();
        factory.getPen().write();

        StationeryFactory factory1 = new BlueFactory();
        factory1.getEraser().raclage();
        factory1.getPen().write();
    }
}

结果

在这里插入图片描述

抽象工厂模式

代码
形状接口

/**
 * 形状接口
 */
public interface Shape {
    void draw();
}

实现

public class Circle implements Shape {
    public void draw() {
        System.out.println("Circle : draw method");
    }
}
public class Rectangle implements Shape {
    public void draw() {
        System.out.println("Rectangle : draw method");
    }
}
public class Square implements Shape {
    public void draw() {
        System.out.println("Square : draw method");
    }
}

颜色接口

/**
 * 颜色接口
 */
public interface Color {
    void fill();
}

实现

public class Red implements Color {
    public void fill() {
        System.out.println("Red : fill method");
    }
}

public class Green implements Color {
    public void fill() {
        System.out.println("Green : fill method");
    }
}

public class Blue implements Color {
    public void fill() {
        System.out.println("Blue : fill method");
    }
}

抽象工厂

/**
 * 抽象工厂
 */
public abstract class AbstractFactory {
    abstract Color getColor(String color);

    abstract Shape getShape(String shape);
}

形状工厂

/**
 * 形状工厂
 */
public class ShapeFactory extends AbstractFactory{

    Color getColor(String color) {
        return null;
    }

    Shape getShape(String shape) {
        if (shape == null){
            return null;
        }else if ("CIRCLE".equals(shape)){
            return new Circle();
        }else if ("SQUARE".equals(shape)){
            return new Square();
        }else if ("RECTANGLE".equals(shape)){
            return new Rectangle();
        }
        return null;
    }
}

颜色工厂

/**
 * 颜色工厂
 */
public class ColorFactory extends AbstractFactory {
    Color getColor(String color) {
        if ("RED".equals(color)){
            return new Red();
        }else if ("BLUE".equals(color)){
            return new Blue();
        }else if ("GREEN".equals(color)){
            return new Green();
        }
        return null;
    }

    Shape getShape(String shape) {
        return null;
    }
}

产品工厂

/**
 * 产品工厂
 */
public class FactoryProducer {
    public static AbstractFactory getFactory(String choice){
        if(choice.equalsIgnoreCase("SHAPE")){
            return new ShapeFactory();
        } else if(choice.equalsIgnoreCase("COLOR")){
            return new ColorFactory();
        }
        return null;
    }
}

测试

public class Test {
    public static void main(String[] args) {
        AbstractFactory shape = FactoryProducer.getFactory("SHAPE");
        AbstractFactory color = FactoryProducer.getFactory("COLOR");
        shape.getShape("CIRCLE").draw();
        shape.getShape("RECTANGLE").draw();
        shape.getShape("SQUARE").draw();
        color.getColor("RED").fill();
        color.getColor("BLUE").fill();
        color.getColor("GREEN").fill();
    }
}

结果
在这里插入图片描述

记录学习过程,参考
http://www.runoob.com/design-pattern/abstract-factory-pattern.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值