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

抽象工厂模式

1.来个手机接口

public interface Phone {
    void  createPhone();
}

2.来个华为手机类 

public class HuaWeiPhone implements Phone {
    private static final String TAG = "HuaWeiPhone";
    @Override
    public void createPhone() {
        Log.e(TAG, "createPhone: " );
    }
}

3.来个小米手机类 

public class XiaoMiPhone implements Phone{
    private static final String TAG = "XiaoMiPhone";
    @Override
    public void createPhone() {
        Log.e(TAG, "createPhone: " );
    }
}

4.来个电脑接口 

public interface Pc {
    void createPc();
}

5.来个华为电脑类 

public class HuaWeiPc implements Pc {
    private static final String TAG = "HuaWeiPc";
    @Override
    public void createPc() {
        Log.e(TAG, "createPc: " );
    }
}

6.来个小米电脑类 

public class XiaoMiPc implements Pc {
    private static final String TAG = "XiaoMiPc";
    @Override
    public void createPc() {
        Log.e(TAG, "createPc: " );
    }
}

7. 工厂可能不仅仅只做手机,它还要做电脑,可能也要做其他的电子产品.  把所有的产品抽象到抽象工厂里面.

public abstract class AbstractFactory {
   abstract Phone createPhone();
   abstract Pc createPc();
}

8.实现华为工厂 

public class HuaWeiFactory extends AbstractFactory {
    @Override
    public Phone createPhone() {
        return new HuaWeiPhone();
    }

    @Override
    public Pc createPc() {
        return new HuaWeiPc();
    }
}

9. 实现小米工厂

public class XiaoMiFactory extends AbstractFactory {
    @Override
    public Phone createPhone() {
        return new XiaoMiPhone();
    }

    @Override
    public Pc createPc() {
        return new XiaoMiPc();
    }
}

10.来个测试类, 想要小米手机就可以用小米工厂来做,想华为电脑就用华为工厂来做.

public class Test {
    public void test() {
        HuaWeiFactory huaWeiFactory = new HuaWeiFactory();
        HuaWeiPhone huaWeiPhone = (HuaWeiPhone) huaWeiFactory.createPhone();
        HuaWeiPc huaWeiPc = (HuaWeiPc) huaWeiFactory.createPc();

        XiaoMiFactory xiaoMiFactory = new XiaoMiFactory();
        XiaoMiPhone xiaoMiPhone = (XiaoMiPhone) xiaoMiFactory.createPhone();
        XiaoMiPc xiaoMiPc = (XiaoMiPc) xiaoMiFactory.createPc();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值