设计模式----抽象工厂模式

工厂方法是具体工厂负责生产具体的产品,每个工厂都负责一种产品,而这些产品都属于同一类。抽象工厂和工厂方法的区别是抽象工厂又对所有类别的工厂进行了封装,可以生产一族产品,如下图所示生产手机和笔记本电脑两种物品

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
华为智能手表开机

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值