工厂可以创建同一系列的具体产品,工厂根据具体参数,创建相应的产品
没有工厂接口,只是一个工厂创建多个具体产品
例子:一个饭店(工厂)--一个卖饭窗口(产品接口)--炒鸡蛋,炒五花肉(产品,一系列具体种类)
interface IFood{ public void food(); } class Eggs implements IFood{ public void food(){ System.out.println("eggs"); } } class Meat implements IFood{ public void food(){ System.out.println("meat"); } } class FoodStore{ public IFood getFood(int i){ if(i==1){ return new Meat(); } if(i==2){ return new Eggs(); } return null; } public static void main(String args[]){ //去饭店ef--点饭getFood--开吃food EatFactory ef=new EatFactory(); ef.getFood(1).food(); ef.getFood(2).food(); } }
二、工厂模式
具体工厂生产一种具体产品
例子:一个饭店接口--炒鸡蛋店(具体工厂),炒肉店(具体工厂)
interface IEat{ public void eat(); } class Eggs implements IEat{ public void eat(){ System.out.println("eggs"); } } class Meat implements IEat{ public void eat(){ System.out.println("meat"); } } /** *工厂接口,与工厂具体实现 *对吃没有要求,肉蛋均可 *每一个具体工厂对应一个具体产品 */ interface IFactory{ public IEat createFood(); } class EggsFactory implements IFactory{ public IEat createFood(){ return new Eggs(); } public static void main(String args[]){ //进了肉店吃炒肉 IFactory factory=new MeatFactory(); factory.createFood(); } } class MeatFactory implements IFactory{ public IEat createFood(){ return new Meat(); } }
三、抽象工厂模式
出现了产品簇,多个产品簇的等级结构相同
例子:
将肉蛋组合成产品并分类……鸡品、鸭品
它们的等级结构都是肉蛋
所以抽象工厂的行为是造肉,造蛋
具体工厂为吃鸡工厂,吃鸭工厂
interface IEgg{ public void eatEgg(); } interface IMeat{ public void eatMeat(); } class ChickenEggs implements IEgg{ public void eatEgg(){ System.out.println("chicken henapple"); } } class DuckEggs implements IEgg{ public void eatEgg(){ System.out.println("duck egg"); } } class ChickenMeat implements IMeat{ public void eatMeat(){ System.out.println("chicken meat"); } } class DuckMeat implements IMeat{ public void eatMeat(){ System.out.println("duck meat"); } } /** *抽象工厂,创建的是 *一个产品簇就是(一个整体中的)多个模块--------这里是蛋和肉组成一个产品肉蛋 *多个等级结构---------------这里产品的等级结构都是蛋和肉 *等级结构相同,所有使用抽象工厂模式 */ interface IAbstractFactory{ public IEgg createEgg(); public IMeat createMeat(); } class ChickenFactory implements IAbstractFactory{ public IEgg createEgg(){ return new ChickenEggs(); } public IMeat createMeat(){ return new ChickenMeat(); } public static void main(String args[]){ //进了鸡店吃鸡蛋,吃鸡肉 IAbstractFactory factory=new ChickenFactory(); IEgg egg=factory.createEgg(); IMeat meat=factory.createMeat(); egg.eatEgg(); meat.eatMeat(); } } class DuckFactory implements IAbstractFactory{ public IEgg createEgg(){ return new DuckEggs(); } public IMeat createMeat(){ return new DuckMeat(); } }
E:\test>javac sic.java
E:\test>java ChickenFactory
chicken henapple
chicken meat
E:\test>