听风的歌

欣赏永运比跟风好

◎Design Pattern: Abstract Factory 模式

我们平日走在步人街上都能看到很多专卖店,服装、珠宝等等;
拿服装专卖店来说,一个专卖店里面肯定有好几个品牌的服装,比如Giordano、Baleno,这些品牌都是不同公司生产的。
没人见个专卖店自己生产服装的吧,专卖店需要某个品牌的服装时,就去联系相应的厂家供货即可,具体的生产是由厂家去完成。
抽象工厂模式也是如此,抽象工厂提供多个抽象方法,由具体的子工厂去实现。
现在我想开一家服装店,经营上衣和短裤,至于具体什么品牌的等选门面在装修之时再定。
interface ISpecialityShop {
   Shirt createShirt();
   Pants createPants();
}

好了,现在门面选好且已装修完毕,具体经营什么品牌也早想好,就佐丹奴和班尼路吧。
开始联系厂家,厂家要能生产Shirt和Pants,而且要有生产Giordano、Baleno这两个品牌。

我们都知道服装都有一些共同的特征,每件衣服都有所属的品牌、每条短裤都有一个尺码。

interface Shirt {
   
// 品牌
   String getBrand();
}

interface Pants {
   
// 尺寸
   double getSize(); 
}

佐丹奴的衣服自然会印上Giordano字样的标志

class GiordanoTShirt implements Shirt {
   
public String getBrand() {
       
return "Giordano";
   }
}

class GiordanoPants implements Pants {
   
public double getSize() {
       
return 31;
   }
}

班尼路的也不例外,加上自己的品牌标志

class BalenoTShirt implements Shirt {
   
public String getBrand() {
       
return "Baleno";
   }
}

class BalenoPants implements Pants {
   
public double getSize() {
       
return 29;
   }
}


运气不错,很快就找到了厂家。

// 生产Giordano上衣和短裤的工厂

class GiordanoFactory implements ISpecialityShop {
   Shirt createShirt() {
      
return new GiordanoTShirt();
   }
   
   Pants createPants() {
      
return new GiordanoPants();
   }
}

// 生产Baleno上衣和短裤的工厂
class BalenoFactory implements ISpecialityShop {
   Shirt createShirt() {
      
return new BalenoTShirt();
   }
   
   Pants createPants() {
      
return new BanlenoPants();
   }
}


厂家开始供货,开业大吉,哈哈。

public class TestAbstractFactory extends TestCase {
 
public static void main(String[] args) {
  TestRunner.run(TestAbstractFactory.
class);
 }

 
public void testFac() {
  setShop(
new GiordanoFactory());
  IShirt shirt 
= shopFactory.createShirt();
  shirt.getBrand();
  IPants pants 
= shopFactory.createPants();
  pants.getSize();
  
  setShop(
new BalenoFactory());
  shirt 
= shopFactory.createShirt();
  shirt.getBrand();
  pants 
= shopFactory.createPants();
  pants.getSize();
 }
 
 
private void setShop(ISpecialityShop factory) {
  shopFactory 
= factory;
 }

 
protected void setUp() throws Exception {
  
 }

 
protected void tearDown() throws Exception {
  shopFactory 
= null;  
 }
 
private ISpecialityShop shopFactory;
}


以后想多经营几个品牌,只需直接去找了厂家供货即可。


最后,为了充分理解抽象工厂模式,画出它的UML图是很有必要的。




posted on 2007-04-19 15:24 听风的歌 阅读(345) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

<2007年4月>
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

统计

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜