抽象工厂模式
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();
}
}