/**
* 主要思路:先构建一个总工厂,包含许多分工厂,再从分工厂中,取出自己想要的类型的物品
*/
public class main {
public static void main(String[] args) {
FactoryProducer factoryProducer = new FactoryProducer();
//获取手机工厂
AbstractFactory phoneFactory = factoryProducer.getFactory("Phone");
//获取路由器工厂
AbstractFactory routerFactory = factoryProducer.getFactory("Router");
//手机工厂创建对应的手机
phoneFactory.createPhone("xiaomi");
//路由器工厂创建对应路由器
routerFactory.createRouter("xiaomi");
}
}
//生产手机的接口
public interface Phone { void call(); void hangup(); void sendSMS(); }
不同厂商的手机
public class huaweiPhone implements Phone {
@Override
public void call() {
System.out.println("huaweiPhone call");
}
@Override
public void hangup() {
System.out.println("huaweiPhone playGame");
}
@Override
public void sendSMS() {
System.out.println("huaweiPhone sendMsg");
}
}
public class xiaomiPhone implements Phone {
@Override
public void call() {
System.out.println("xiaomiPhone call");
}
@Override
public void sendSMS() {
System.out.println("xiaomiPhone sendMsg");
}
@Override
public void hangup() {
System.out.println("xiaomiPhone playGame");
}
}
//创建手机的工厂 public class PhoneFactoryImpl implements AbstractFactory { @Override public Phone createPhone(String phoneType) { if("huawei".equals(phoneType)){ return new huaweiPhone(); }else if("xiaomi".equals(phoneType)) { return new xiaomiPhone(); } return null; } @Override public Router createRouter(String routerType) { return null; } }
//路由器接口
public interface Router { void on(); void off(); void onWifi(); void offWifi(); }
//不同厂商路由器
public class huaweiRouter implements Router {
public void on() {
System.out.println("huaweiRouter on");
}
public void off() {
System.out.println("huaweiRouter off");
}
public void onWifi() {
System.out.println("huaweiRouter onWifi");
}
public void offWifi() {
System.out.println("huaweiRouter offWifi");
}
}
public class xiaomiRouter implements Router {
@Override
public void on() {
System.out.println("xiaomiRouter on");
}
@Override
public void off() {
System.out.println("xiaomiRouter off");
}
@Override
public void onWifi() {
System.out.println("xiaomiRouter onWifi");
}
@Override
public void offWifi() {
System.out.println("xiaomiRouter offWifi");
}
}
//创建路由器工厂 public class RouterFactoryImpl implements AbstractFactory { @Override public Phone createPhone(String phoneType) { return null; } @Override public Router createRouter(String routerType) { if("xiaomi".equals(routerType)){ return new xiaomiRouter(); } else if ("huawei".equals(routerType)) { return new huaweiRouter(); } return null; } }
//工厂生产者 public class FactoryProducer { public static AbstractFactory getFactory(String factory) { if (factory.equalsIgnoreCase("Phone")) { return new PhoneFactoryImpl(); } else if (factory.equalsIgnoreCase("Router")) { return new RouterFactoryImpl(); } return null; } }