工厂接口类
public interface ProductFactory {Phone phoneProduct();//生产手机Router routerProduct();//生产路由器
}
小米工厂实现类
public class XiaomiFactoryImpl implements ProductFactory {@Overridepublic Phone phoneProduct() {return new XiaomiPhoneImpl();}@Overridepublic Router routerProduct() {return new XiaomiRouterImpl();}
}
华为工厂实现类
public class HuaweiFactoryImpl implements ProductFactory {@Overridepublic Phone phoneProduct() {return new HuaweiPhoneImpl();}@Overridepublic Router routerProduct() {return new HuaweiRouterImpl();}
}
手机接口类
public interface Phone {void start();//开机void callUp();//打电话
}
小米手机实现类
public class XiaomiPhoneImpl implements Phone {@Overridepublic void start() {System.out.println("小米手机开机...");}@Overridepublic void callUp() {System.out.println("小米手机打电话...");}
}
华为手机实现类
public class HuaweiPhoneImpl implements Phone {@Overridepublic void start() {System.out.println("华为手机开机...");}@Overridepublic void callUp() {System.out.println("华为手机打电话...");}
}
路由器接口类
public interface Router {void start();//开机void openWifi();//打开WiFi
}
小米路由器实现类
public class XiaomiRouterImpl implements Router {@Overridepublic void start() {System.out.println("小米路由器开机...");}@Overridepublic void openWifi() {System.out.println("小米路由器打开WiFi...");}
}
华为路由器实现类
public class HuaweiRouterImpl implements Router {@Overridepublic void start() {System.out.println("华为路由器开机...");}@Overridepublic void openWifi() {System.out.println("华为路由器打开WiFi...");}
}
演示类
public class Demo {public static void main(String[] args) {ProductFactory xiaomiFactory = new XiaomiFactoryImpl();ProductFactory huaweiFactory = new HuaweiFactoryImpl();//小米工厂生产手机Phone xiaomiPhone = xiaomiFactory.phoneProduct();xiaomiPhone.start();xiaomiPhone.callUp();//小米工厂生产路由器Router xiaomiRouter = xiaomiFactory.routerProduct();xiaomiRouter.start();xiaomiRouter.openWifi();//华为工厂生产手机Phone huaweiPhone = huaweiFactory.phoneProduct();huaweiPhone.start();huaweiPhone.callUp();//华为工厂生产路由器Router huaweiRouter = huaweiFactory.routerProduct();huaweiRouter.start();huaweiRouter.openWifi();}
}
演示结果: