工厂方法模式
1.来个实物类接口
public interface Phone {
void call();
}
2.实现接口,来个华为手机类
public class HuaWeiPhone implements Phone {
private static final String TAG = "HuaWeiPhone";
@Override
public void call() {
Log.e(TAG, "call: " );
}
}
3.来个小米手机类
public class XiaoMiPhone implements Phone {
private static final String TAG = "XiaoMiPhone";
@Override
public void call() {
Log.e(TAG, "call: " );
}
}
4.简单工厂然我们扩展起来很麻烦,就是说我要再来一个是个工厂手机,我不就得去改原来的代码? (三个月自己写的,我自己都看不懂了) 不想改,那我就让工厂也变成接口,下次要加任何手机进来, 我只要新开一个工厂就好.
public interface AbstractCreatePhoneFactory {
Phone createPhone();
}
5. 实现小米工厂
public class XiaoMiFactory implements AbstractCreatePhoneFactory {
@Override
public Phone createPhone() {
return new XiaoMiPhone();
}
}
6.实现华为工厂
public class HuaWeiFactory implements AbstractCreatePhoneFactory {
@Override
public Phone createPhone() {
return new HuaWeiPhone();
}
}
7.测试类来一个,这样要小米手机就让小米工厂去创建,要华为手机就让华为工厂去创建
public class Test {
public void test() {
XiaoMiFactory xiaoMiFactory = new XiaoMiFactory();
XiaoMiPhone xiaoMiPhone = (XiaoMiPhone) xiaoMiFactory.createPhone();
HuaWeiFactory huaWeiFactory = new HuaWeiFactory();
HuaWeiPhone huaWeiPhone = (HuaWeiPhone) huaWeiFactory.createPhone();
}
}