工厂接口类
- public interface ProductFactory {
- Phone phoneProduct();//生产手机
-
- Router routerProduct();//生产路由器
- }
小米工厂实现类
- public class XiaomiFactoryImpl implements ProductFactory {
- @Override
- public Phone phoneProduct() {
- return new XiaomiPhoneImpl();
- }
-
- @Override
- public Router routerProduct() {
- return new XiaomiRouterImpl();
- }
- }
华为工厂实现类
- public class HuaweiFactoryImpl implements ProductFactory {
- @Override
- public Phone phoneProduct() {
- return new HuaweiPhoneImpl();
- }
-
- @Override
- public Router routerProduct() {
- return new HuaweiRouterImpl();
- }
- }
手机接口类
- public interface Phone {
- void start();//开机
-
- void callUp();//打电话
- }
小米手机实现类
- public class XiaomiPhoneImpl implements Phone {
- @Override
- public void start() {
- System.out.println("小米手机开机...");
- }
-
- @Override
- public void callUp() {
- System.out.println("小米手机打电话...");
- }
- }
华为手机实现类
- public class HuaweiPhoneImpl implements Phone {
- @Override
- public void start() {
- System.out.println("华为手机开机...");
- }
-
- @Override
- public void callUp() {
- System.out.println("华为手机打电话...");
- }
- }
路由器接口类
- public interface Router {
- void start();//开机
-
- void openWifi();//打开WiFi
- }
小米路由器实现类
- public class XiaomiRouterImpl implements Router {
- @Override
- public void start() {
- System.out.println("小米路由器开机...");
- }
-
- @Override
- public void openWifi() {
- System.out.println("小米路由器打开WiFi...");
- }
- }
华为路由器实现类
- public class HuaweiRouterImpl implements Router {
- @Override
- public void start() {
- System.out.println("华为路由器开机...");
- }
-
- @Override
- public 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();
-
- }
- }
演示结果: