持续感冒中。。。,又是头晕的一天,明天中午还是要打乒乓球
大伙可能听说过简单工厂模式,我的比较浅薄的理解就是实际产品类继承于产品接口,但工厂类的生产方法是静态方法,通过传入参数来决定要生产的产品,当有新的产品需要生产时,需要的是修改而不是新增,不符合设计原则的开闭原则。来看Factory Method模式,这是在简单工厂模式上的一种改进。
既然每次有新的产品都需要修改工厂类的生产方法,那我们可以将工厂类提取为一个接口,每有新的产品都为它新建一个工厂,来看一个生产ID卡的例子,顺便复习下之前的template method模式。
老规矩,直接上代码,先看下Product接口:
public interface Product {
public abstract void use();
}
定义了产品的含义:能用即可,产品,就是可以调用use方法的对象。
再来看工厂抽象类:
public abstract class Factory {
protected abstract Product createProduct(String owner);
protected abstract void registerProduct(Product product);
public final Product create(String owner) {
Product p = createProduct(owner);
registerProduct(p);
return p;
}
}
这里书上为了与之前的template method模式联系起来,将工厂抽象类写成了如上的形式,但也增高了耦合性,其实我个人认为只有create方法足矣。
接下来就是具体产品和具体工厂的细节实现:
public class IDCard implements Product {
private String owner;
public IDCard(String owner) {
this.owner = owner;
}
@Override
public void use() {
System.out.println("使用" + this.owner + "ID卡");
}
public String getOwner() {
return this.owner;
}
}
import java.util.ArrayList;
import java.util.List;
/**
* @author lenovo
* @title: IDCardFactory
* @projectName LearnDesignMode
* @description: TODO
* @date 2022/5/520:56
*/
public class IDCardFactory extends Factory {
private List<Product> owners = new ArrayList<Product>();
@Override
protected Product createProduct(String owner) {
return new IDCard(owner);
}
@Override
protected void registerProduct(Product product) {
this.owners.add(product);
}
}
来测试一下:
public class Main {
public static void main(String[] args) {
Factory factory = new IDCardFactory();
Product IDCard_1 = factory.create("yuzhe");
Product IDCard_2 = factory.create("ziyou");
Product IDCard_3 = factory.create("cibei");
IDCard_1.use();
IDCard_2.use();
IDCard_3.use();
}
}
结果如下:
使用yuzheID卡
使用ziyouID卡
使用cibeiID卡
以上是书上的例子,现在来增加一个新的产品,验证一下该模式较之简单工厂模式的优势:
public class Car implements Product {
private String owner;
public Car(String owner) {
this.owner = owner;
}
@Override
public void use() {
System.out.println(this.owner + "的car被使用");
}
}
public class CarFactory extends Factory {
private List<Product> cars = new ArrayList<Product>();
@Override
protected Product createProduct(String owner) {
return new Car(owner);
}
@Override
protected void registerProduct(Product product) {
this.cars.add(product);
}
}
public class Main {
public static void main(String[] args) {
Factory carFactory = new CarFactory();
Product car1 = carFactory.create("xiaoming");
Product car2 = carFactory.create("hahaha");
Product car3 = carFactory.create("niwa");
car1.use();
car2.use();
car3.use();
}
}
测试结果:
xiaoming的car被使用
hahaha的car被使用
niwa的car被使用