工厂方法是具体工厂负责生产具体的产品,每个工厂都负责一种产品,而这些产品都属于同一类。抽象工厂和工厂方法的区别是抽象工厂又对所有类别的工厂进行了封装,可以生产一族产品,如下图所示生产手机和笔记本电脑两种物品
1、建立一个抽象工厂,包含多个抽象类别
public interface AbstractFactory {
MobilePhone getMobilePhone();
Laptop getLaptop();
}
2、建立对应的抽象类
public abstract class Laptop {
private String brand;
public Laptop(String brand){
this.brand = brand;
}
public abstract String getId();
public void getDescription(){
System.out.println("this is a " + brand + "Laptop");
};
}
public abstract class MobilePhone {
public abstract void activate();
}
3、建立具体的产品(这里用到了多线程安全创建,学习阶段不考虑性能)
public class HuaweiLaptop extends Laptop {
private static final String brand = "huawei";
protected static AtomicInteger initId = new AtomicInteger(100);
public HuaweiLaptop() {
super(brand);
// initId.set(100);
}
@Override
public String getId() {
return "huawei--" + (initId.addAndGet(1));
}
}
public class HuaweiPhone extends MobilePhone{
@Override
public void activate() {
System.out.println("激活华为手机");
}
}
4、建立一个具体工厂用于生产具体的产品
public class HuaweiFactory implements AbstractFactory {
@Override
public MobilePhone getMobilePhone() {
return new HuaweiPhone();
}
@Override
public Laptop getLaptop() {
return new HuaweiLaptop();
}
@Override
public Watch getWatch() {
return new HuaweiWatch();
}
}
测试:
public class Test {
public static void main(String[] args) {
//create a huawei factory
AbstractFactory f = new HuaweiFactory();
for (int i = 0; i < 5; i++) {
new Thread(()->{
synchronized (f){
//create a huawei product
MobilePhone mobilePhone = f.getMobilePhone();
mobilePhone.activate();
System.out.println(mobilePhone.toString());
f.getLaptop().getDescription();
System.out.println(f.getLaptop().getId());
Watch watch = f.getWatch();
watch.open();
}
}).start();
}
}
测试结果:(这里我尝试增加一个新的类别产品手表,结果输出如下)
激活华为手机
Factory.AbstractFactory.HuaweiPhone@7a024d7
this is a huaweiLaptop
huawei--101
华为智能手表开机
激活华为手机
Factory.AbstractFactory.HuaweiPhone@4f7a3a41
this is a huaweiLaptop
huawei--102
华为智能手表开机
激活华为手机
Factory.AbstractFactory.HuaweiPhone@2549266
this is a huaweiLaptop
huawei--103
华为智能手表开机
激活华为手机
Factory.AbstractFactory.HuaweiPhone@6d629d4e
this is a huaweiLaptop
huawei--104
华为智能手表开机
激活华为手机
Factory.AbstractFactory.HuaweiPhone@2364ab86
this is a huaweiLaptop
huawei--105
华为智能手表开机