一、工厂方法模式
interface BeerFactory{
void createBeer();
}
class QingDaoBeerFactory implements BeerFactory{
@Override
public void createBeer() {
System.out.println("青岛啤酒厂生产啤酒");
}
}
class XueHuaBeerFactory implements BeerFactory{
@Override
public void createBeer() {
System.out.println("雪花啤酒厂生产啤酒");
}
}
class FactoryMethod{
public static void main(String[] args) {
BeerFactory qingDao=new QingDaoBeerFactory();
BeerFactory xueHua=new XueHuaBeerFactory();
}
}
二、抽象工厂模式
//啤酒发酵工艺
interface IFermentBeer{
void fermentBeer();
}
//啤酒装瓶工艺
interface IFillBeer{
void fillBeer();
}
//制作啤酒
interface ICreateBeer{
IFermentBeer getFermentBeer();
IFillBeer getFillBeer();
}
//青岛啤酒发酵
class QingDaoFactoryFermentBeer implements IFermentBeer{
@Override
public void fermentBeer() {
System.out.println("青岛啤酒的发酵工艺");
}
}
//青岛啤酒装罐
class QingDaoFactoryFillBeer implements IFillBeer{
@Override
public void fillBeer() {
System.out.println("青岛啤酒的装罐工艺");
}
}
//青岛啤酒生产
class QingDaoFactoryCreateBeer implements ICreateBeer{
@Override
public IFermentBeer getFermentBeer() {
return new QingDaoFactoryFermentBeer();
}
@Override
public IFillBeer getFillBeer() {
return new QingDaoFactoryFillBeer();
}
}
//青岛啤酒发酵
class XueHuaFactoryFermentBeer implements IFermentBeer{
@Override
public void fermentBeer() {
System.out.println("雪花啤酒的发酵工艺");
}
}
//青岛啤酒装罐
class XueHuaFactoryFillBeer implements IFillBeer{
@Override
public void fillBeer() {
System.out.println("雪花啤酒的装罐工艺");
}
}
//青岛啤酒生产
class XueHuaFactoryCreateBeer implements ICreateBeer{
@Override
public IFermentBeer getFermentBeer() {
return new XueHuaFactoryFermentBeer();
}
@Override
public IFillBeer getFillBeer() {
return new XueHuaFactoryFillBeer();
}
}
class BeerFactoryMethod{
public static void main(String[] args) {
ICreateBeer qingDao=new QingDaoFactoryCreateBeer();
qingDao.getFermentBeer();
qingDao.getFillBeer();
ICreateBeer xueHua=new XueHuaFactoryCreateBeer();
xueHua.getFermentBeer();
xueHua.getFillBeer();
}
}