首页 > 其他 > 详细

设计模式之工厂模式

时间:2020-12-09 15:03:12      阅读:27      评论:0      收藏:0      [点我收藏+]

工厂模式提供了创建对象的最佳方式,创建对象时不会向客户端暴露创建逻辑,并且通过一个共同的接口指向新创建的对象。

1、创建一个接口

public interface Shape {
    void draw();
}

2、具体的对象

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

3、定义工厂类

public class ShapeFactory {
    
    public Shape getShape(String shapeType) {
        if (null == shapeType) {
            return null;
        }

        switch (shapeType) {
            case "CIRCLE":
                return new Circle();
            case "RECTANGLE":
                return new Rectangle();
            case "SQUARE":
                return new Square();
            default:
                return null;
        }
    }
}

4、测试

public class _Test {
    public static void main(String[] args) {
        ShapeFactory factory = new ShapeFactory();
        Shape shape1 = factory.getShape("CIRCLE");
        shape1.draw();
        Shape shape2 = factory.getShape("RECTANGLE");
        shape2.draw();
        Shape shape3 = factory.getShape("SQUARE");
        shape3.draw();
    }
}

 

设计模式之工厂模式

原文:https://www.cnblogs.com/lyy12332133/p/14107926.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!