packagecn.imcompany;/**
* Created by tomyli on 2018/5/27.
* Github: https://github.com/peng051410
*/publicinterfaceBeer{StringgetName();}publicclassJinShiBaiimplementsBeer{@OverridepublicStringgetName(){return"金士百";}}publicclassQingDaoimplementsBeer{@OverridepublicStringgetName(){return"青岛";}}publicclassBaiWeiimplementsBeer{@OverridepublicStringgetName(){return"百威";}}
packagecn.imcompany.simple;importcn.imcompany.BaiWei;importcn.imcompany.Beer;importcn.imcompany.JinShiBai;importcn.imcompany.QingDao;/**
* 一个工厂什么都生产,根据传入的参数来返回不同的产品
* Created by tomyli on 2018/5/28.
* Github: https://github.com/peng051410
*/publicclassSimpleFactory{publicstaticBeergetBeer(Stringname){if("青岛".equals(name)){returnnewQingDao();}elseif("百威".equals(name)){returnnewBaiWei();}elseif("金士百".equals(name)){returnnewJinShiBai();}else{System.out.println("没有这种啤酒");returnnull;}}}
在上面的代码简单工厂会根据传入的啤酒名称来生产出不同的啤酒。下面来测试一下这个简单工厂
1
2
3
4
5
6
7
8
9
10
11
12
13
packagecn.imcompany.simple;/**
* Created by tomyli on 2018/5/28.
* Github: https://github.com/peng051410
*/publicclassSimpleFactoryTest{publicstaticvoidmain(String[]args){System.out.println(SimpleFactory.getBeer("青岛"));}}
/**
* 定义获取的功能,具体由实现类(具体的啤酒厂)来实现,做到创建与使用隔离
* Created by tomyli on 2018/5/28.
* Github: https://github.com/peng051410
*/publicabstractclassFunctionFactory{publicabstractBeergetBeer();}publicclassBaiWeiFactoryextendsBeerFactory{@OverridepublicBeergetBeer(){returnnewBaiWei();}}publicclassJinShiBaiFactoryextendsBeerFactory{@OverridepublicBeergetBeer(){returnnewJinShiBai();}}publicclassQinDaoFactoryextendsBeerFactory{@OverridepublicBeergetBeer(){returnnewQingDao();}}
packagecn.imcompany.function;/**
* Created by tomyli on 2018/5/28.
* Github: https://github.com/peng051410
*/publicclassFunctionFactoryTest{publicstaticvoidmain(String[]args){BeerFactoryjinShiBaiFactory=newJinShiBaiFactory();System.out.println(jinShiBaiFactory.getBeer());}}
packagecn.imcompany.abs;importcn.imcompany.Beer;/**
* Created by tomyli on 2018/5/28.
* Github: https://github.com/peng051410
*/publicinterfaceAbstractBeerFactory{BeergetQingDao();BeergetBaiWei();BeergetJinShiBai();}packagecn.imcompany.abs;importcn.imcompany.BaiWei;importcn.imcompany.Beer;importcn.imcompany.JinShiBai;importcn.imcompany.QingDao;/**
* Created by tomyli on 2018/5/28.
* Github: https://github.com/peng051410
*/publicclassConcreteBeerFactoryimplementsAbstractBeerFactory{@OverridepublicBeergetQingDao(){returnnewQingDao();}@OverridepublicBeergetBaiWei(){returnnewBaiWei();}@OverridepublicBeergetJinShiBai(){returnnewJinShiBai();}}
packagecn.imcompany.abs;/**
* Created by tomyli on 2018/5/28.
* Github: https://github.com/peng051410
*/publicclassAbstractFactoryTest{publicstaticvoidmain(String[]args){AbstractBeerFactorybeerFactory=newConcreteBeerFactory();System.out.println(beerFactory.getBaiWei());}}