工厂模式的含义:定义一个接口,以及其实现类。创建工厂定位接口实现类并实例化。用户传参数给工厂,获得所需要的实例对象。
比如:一个汽车配件工厂,客户根据自己的需求选择配件。一个Shape接口,其实现类有Circle,Squsre,Rectangle。然后创建一个工厂,用来定位需要那种实现类。这样通过实例化工厂,选择不同的参数,然后根据参数选择具体的实现类。也就是说通过工厂类来分配对象。
优点:一个调用者想要创建对象,只要知道其名称就可以了,扩展性高,如果想要增加一个产品,只要扩展一个工程类就可以了,屏蔽产品的具体实现,调用这只需要关心接口就可以了。
缺点:每次增加一个产品时,都需要增加一个具体类和对象实现工厂,使得系统中类的个数成倍增加,在一定程度上增加了系统的复杂度,同时也增加了系统具体类的依赖。
eg:
//创建工厂
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 {
//使用 getShape 方法获取形状类型的对象
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();
//获取 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();
}
}