工厂模式

it2026-01-20  11

工厂模式是JAVA中最常用的设计模式。工厂模式是基于创建模式的,它提供了创建对象的最佳途径。

在工厂模式中,创建对象无需向对象的使用者暴露该对象的创建逻辑,只需提供一个公共的创建接口即可。

 

【实现】

我们将创建一个图形接口及实现了该接口的一批实体类,然后定义一个图形工厂,该工厂会接收创建信息(圆/长方形/正方形)并基于该信息为消费者提供其需要的对象,如下图所示:

 

【第一步】,创建图形接口

public interface Shape { void draw(); }

【第二步】,创建实现了该接口的一批实体类

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."); } } public class Circle implements Shape { @Override public void draw() { System.out.println("Inside Circle::draw() method."); } }

【第三步】,创建图形工厂,该工厂依据消费者提供的信息返回与之匹配的对象

public class ShapeFactory { //use getShape method to get object of type shape public Shape getShape(String shapeType){ if(shapeType == null){ return null; } if(shapeType.equalsIgnoreCase("CIRCLE")){ return new Circle(); } else if(shapeType.equalsIgnoreCase("RECTANGLE")){ return new Rectangle(); } else if(shapeType.equalsIgnoreCase("SQUARE")){ return new Square(); } return null; } }

【第四步】,消费者提供创建信息给图形工厂以获取所需的图形实体类

public class FactoryPatternDemo { public static void main(String[] args) { ShapeFactory shapeFactory = new ShapeFactory(); //get an object of Circle and call its draw method. Shape shape1 = shapeFactory.getShape("CIRCLE"); //call draw method of Circle shape1.draw(); //get an object of Rectangle and call its draw method. Shape shape2 = shapeFactory.getShape("RECTANGLE"); //call draw method of Rectangle shape2.draw(); //get an object of Square and call its draw method. Shape shape3 = shapeFactory.getShape("SQUARE"); //call draw method of circle shape3.draw(); } }

此时,即可看到消费者依次拿到了它所需的图形实体类

Inside Circle::draw() method. Inside Rectangle::draw() method. Inside Square::draw() method.

/*************************外星人乔丹拍板时间***************************/

普通工厂模式的核心意义为:

【一】消费者只需要知道它要什么,而不需要知道它要的东西是如何产生的,类似于软件外包

【二】实现了消费者与其所需要东西的解耦

【三】工厂实现了桥接作用,可以统一的接口服务于多个消费者

转载于:https://www.cnblogs.com/AlienJordan/p/3841551.html

最新回复(0)