工厂模式简介说明
下文笔者讲述工厂模式的简介说明,如下所示
定义一个Shape接口
实现Shape接口实体类
定义工厂类ShapeFactory
工厂模式
工厂模式(Factory Pattern):
是Java中最常用的设计模式之一
工厂模式属于创建型模式,常用于创建对象
工厂模式的实现原理:
1.定义一个创建对象的接口
2.让其子类自己决定实例化哪一个工厂类
工厂模式将创建过程延迟到子类中进行
例:定义一个Shape接口
实现Shape接口实体类
定义工厂类ShapeFactory
使用 ShapeFactory 来获取 Shape 对象 向 ShapeFactory 传递信息(CIRCLE / RECTANGLE / SQUARE) 将返回不同的子对象
接口
Shape.java
public interface Shape {
void draw();
}
接口对应的实体类
Rectangle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Square.java
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
Circle.java
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
ShapeFactory.java
public class ShapeFactory {
//使用 getShape 方法获取形状类型的对象
public Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
shapeType = shapeType.toLowerCase();
switch (shapeType) {
case "circle":
return new Circle();
case "rectangle":
return new Rectangle();
case "square":
return new Square();
default:
return null;
}
}
}
使用该工厂
通过传递类型信息来获取实体类的对象
public class DemoTest {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
//获取 Circle 的对象,并调用它的 draw 方法
Shape shape1 = shapeFactory.getShape("CIRCLE");
//调用 Circle 的 draw 方法
shape1.draw();
//获取 Rectangle 的对象,并调用它的 draw 方法
Shape shape2 = shapeFactory.getShape("RECTANGLE");
//调用 Rectangle 的 draw 方法
shape2.draw();
//获取 Square 的对象,并调用它的 draw 方法
Shape shape3 = shapeFactory.getShape("SQUARE");
//调用 Square 的 draw 方法
shape3.draw();
}
}
----运行以上测试代码,将输出以下信息-----
Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


