publicclassBusimplementsCar{@OverridepublicvoidgotoWork(){
System.out.println("go to work by bus");}}publicclassBikeimplementsCar{@OverridepublicvoidgotoWork(){
System.out.println("go to work by bike");}}//-------------------------------------------publicclassAppleimplementsBreakfast{@Overridepublicvoideat(){
System.out.println("eat breakfast :apple");}}publicclassMilkimplementsBreakfast{@Overridepublicvoideat(){
System.out.println("eat breakfast :milk");}}
二、工厂部分
1、工厂接口
publicinterfaceAbsFactory{public Car getCar();public Breakfast getBreakfast();}
2、工厂实现类
publicclassPoorManFacimplementsAbsFactory{@Overridepublic Car getCar(){returnnewBike();}@Overridepublic Breakfast getBreakfast(){returnnewApple();}}publicclassRichManFacimplementsAbsFactory{@Overridepublic Car getCar(){returnnewBus();}@Overridepublic Breakfast getBreakfast(){returnnewMilk();}}
三、测试部分
publicclassTestDemo{publicstaticvoidmain(String[] args){
AbsFactory factory =newRichManFac();
Car car = factory.getCar();
Breakfast breakfast = factory.getBreakfast();
car.gotoWork();
breakfast.eat();
System.out.println("----------------");
factory =newPoorManFac();
car = factory.getCar();
breakfast = factory.getBreakfast();
car.gotoWork();
breakfast.eat();}}