工厂模式
在明确地计划不同条件下创建不同实例时,使用工厂模式
实现
- 将实体类进行抽象
- 实体类实现接口
- 创建工厂类
- 根据不同参数,返回不同对象
interface Shape {
void draw();
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
class ShapeFactory {
//使用 getShape 方法获取形状类型的对象
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
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();
//获取 Rectangle 的对象,并调用它的 draw 方法
Shape shape2 = shapeFactory.getShape("RECTANGLE");
//调用 Rectangle 的 draw 方法
shape2.draw();
//获取 Square 的对象,并调用它的 draw 方法
Shape shape3 = shapeFactory.getShape("SQUARE");
//调用 Square 的 draw 方法
shape3.draw();
}
}
抽象工厂
将多个🏭进行
抽象,使用不同的实现类,完成不同产品族🏭的创建,再使用🏭生产对象。
- 使用抽象类的方式将多个🏭进行抽象
- 使用工厂的方式实现🏭类
- 根据不同的需要使用🏭的🏭创建🏭
- 然后使用🏭生产对象
