工厂模式

工厂模式

参考 W3c School

 

工厂模式属于 创建型 设计模式

作用:想要一个对象,调用工厂对象,调用方法直接输入对象的名字即可。

例如:找文具厂获取文具【笔记本】,调用完成后,工厂将笔记本对象给你,封装了后面的细节。

 


目录

UML类图

接口Shape

Circle

Square

Rectangle

ShapType

Main

运行


UML类图

 

首先我们来写接口:

接口Shape

public interface Shape {
    /**
     * 绘制图形方法
     */
    public abstract void draw();
}

创建三个实体类:Circle Square Rectangle

Circle

public class Circle implements Shape {
    /**
     * 绘制圆形
     */
    @Override
    public void draw() {
        System.out.println("[Circle] Draw");
    }
}

Square

public class Square implements Shape {
    /**
     * 绘制矩形
     */
    @Override
    public void draw() {
        System.out.println("[Square] Draw");
    }
}

Rectangle

public class Rectangle implements Shape {
    /**
     * 绘制三角形
     */
    @Override
    public void draw() {
        System.out.println("[Rectangle] Draw");
    }
}

创建存储对象字符串的常量类

ShapType

public class ShapeType {
    public static final String CIRCLE = "circle";
    public static final String RECTANGLE = "rectangle";
    public static final String SQUARE = "square";
}

创建工厂类

ShapeFactory

public class ShapeFactory {
    public Shape getShape(String shapeType){
        /* 判断字符串非空 */
        if (shapeType == null){
            return null;
        }
        
        /* 匹配输入的字符串,生成对象 */
        if (CIRCLE.equalsIgnoreCase(shapeType)){
            return new Circle();
        }else if (RECTANGLE.equalsIgnoreCase(shapeType)){
            return new Rectangle();
        }else if (SQUARE.equalsIgnoreCase(shapeType)){
            return new Square();
        }

        /* 没有相关对象,返回空对象 */
        return null;
    }
}

Main

创建 Main 入口的测试执行类

public class ExecuteMain {
    public static void main(String[] args) {
        ShapeFactory shapeFactory = new ShapeFactory();

        Shape circle = shapeFactory.getShape("circle");
        Shape rectangle = shapeFactory.getShape("rectangle");
        Shape square = shapeFactory.getShape("square");
        Shape unKnown = shapeFactory.getShape("unknown");
        circle.draw();
        rectangle.draw();
        square.draw();
        System.out.println(unKnown==null);
    }
}

运行

[Circle] Draw
[Rectangle] Draw
[Square] Draw
true

Process finished with exit code 0

可以看到,工厂中存在的类型能创建出相对应的对象,而不存在的类型将返回 null 。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值