设计模式(简单工厂模式)

来源:互联网 发布:wish数据分析 编辑:程序博客网 时间:2024/05/23 19:17

工厂模式是我们在开发过程中比较常用的一种设计模式, 相对来说也是比较简单的, 主要的核心思想就是工厂创建对象, 不需要我们去一个一个的new出来对象, 这样的好处就是进一步的封装了代码, 不会将我们的对象暴漏给客户端, 从而使我们的代码来说相对比较安全.
其中主要用到的方法和类主要有(以经典的图形举例):
图形有正方形, 长方形, 三角形, 圆 . 我们用简单的两种图形做举例.
工厂模式的创建应用了面向对象的多态属性, 我们需要首先创建一个Shape接口,来对外提供公共的接口

public interface Shape {    void draw();}

创建两个图形类Rectangle 和 Square 分别实现Shape接口:
Square 类

public class Square implements Shape {    @Override    public void draw() {        System.out.println("这是Square类的方法");    }}

Rectangle 类

public class Rectangle implements Shape {    @Override    public void draw() {        System.out.println("这是Rectangle 类的方法");    }    //类自己的方法    public void draw1() {        System.out.println("这是Rectangle 类的draw1方法");    }}

现在所有的零件都齐全了, 就缺少一个工厂来把他们组装到一起了
添加 ShapeFactory 工厂类(这是工厂模式的核心)

public class ShapeFactory {    public Shape getShape (String type){        if (type == null){            return null;        }        //创建Square        if (type.equalsIgnoreCase("Square")){            return new Square();        }        //创建Rectangle        if (type.equalsIgnoreCase("Rectangle")){            return new Rectangle();        }        return null;    }}

写一个Main方法来测试:

public class TestMain {    public static void main(String[] args){        ShapeFactory shapeFactory = new ShapeFactory();        Shape square = shapeFactory.getShape("Square");        square.draw();        Shape rectangle = shapeFactory.getShape("Rectangle");        rectangle.draw();        //调用类自己的方法 ,向下转型就好了        Rectangle rectangle1 = (Rectangle) shapeFactory.getShape("Rectangle");        rectangle1.draw1();    }}

输出

这是Square类的方法这是Rectangle 类的方法这是Rectangle 类的draw1方法

参考 :

https://www.w3cschool.cn/java/java-factory-pattern.html