提供一个创建一系列(相互依赖)对象的接口,而无需指定它们具体的类。
建立一个系统,该系统可以为用户提供西服套装(上衣+裤子)和牛仔套装(上衣+裤子)。
模式的结构中包括四种角色:
抽象产品(Prodcut) :比如上衣和裤子
具体产品(ConcreteProduct) :比如尺寸大小名字都确定的上衣和裤子
抽象工厂(AbstractFactory) :有生产裤子和上衣的方法
具体工厂(ConcreteFactory) :有生产具体尺寸大小和厂家的上衣和裤子
.抽象产品(Product) :
UpperClothes.java
public abstract class UpperClothes{
public abstract int getChestSize();
public abstract int getHeight();
public abstract String getName();
}
Trousers.java
public abstract class Trousers{
public abstract int getWaistSize();
public abstract int getHeight();
public abstract String getName();
}
具体产品(ConcreteProduct)_2: CowboyUpperClothes.java
public class CowboyUpperClothes extends UpperClothes{
private int chestSize;
private int height;
private String name;
CowboyUpperClothes(String name,int chestSize,int height){
this.name=name;
this.chestSize=chestSize;
this.height=height;
}
public int getChestSize(){
return chestSize;
}
public int getHeight(){
return height;
}
public String getName(){
return name;
}
}
具体产品(ConcreteProduct)_3: WesternTrousers.java
public class WesternTrousers extends Trousers{
private int waistSize;
private int height;
private String name;
WesternTrousers(String name,int waistSize,int height){
this.name=name;
this.waistSize=waistSize;
this.height=height;
}
public int getWaistSize(){
return waistSize;
}
public int getHeight(){
return height;
}
public String getName(){
return name;
}
}
抽象工厂(AbstractFactory):ClothesFactory.java
public abstract class ClothesFactory{
public abstract UpperClothes createUpperClothes(int chestSize,int height);
public abstract Trousers createTrousers(int waistSize,int height);
}
具体工厂(ConcreteFactory):
BeijingClothesFactory.java
public class BeijingClothesFactory extends ClothesFactory {
public UpperClothes createUpperClothes(int chestSize,int height){
return new WesternUpperClothes("北京牌西服上衣",chestSize,height);
}
public Trousers createTrousers(int waistSize,int height){
return new WesternTrousers("北京牌西服裤子",waistSize,height);
}
}
ShanghaiClothesFactory.java
public class ShanghaiClothesFactory extends ClothesFactory {
public UpperClothes createUpperClothes(int chestSize,int height){
return new WesternUpperClothes("上海牌牛仔上衣",chestSize,height);
}
public Trousers createTrousers(int waistSize,int height){
return new WesternTrousers("上海牌牛仔裤",waistSize,height);
}
应用_1: Shop.java
public class Shop{
UpperClothes cloth;
Trousers trouser;
public void giveSuit(ClothesFactory factory,int chestSize,int waistSize,int height){
cloth=factory.createUpperClothes(chestSize,height);
trouser=factory.createTrousers(waistSize,height);
showMess();
}
private void showMess(){
System.out.println("<套装信息>");
System.out.println(cloth.getName()+":");
System.out.print("胸围:"+cloth.getChestSize());
System.out.println("身高:"+cloth.getHeight());
System.out.println(trouser.getName()+":");
System.out.print("腰围:"+trouser.getWaistSize());
System.out.println("身高:"+trouser.getHeight());
}
}