积少成多

垃圾堆

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  29 Posts :: 1 Stories :: 5 Comments :: 0 Trackbacks


public
 interface IProduct {
    
public void desc();
}

public class ProductA implements IProduct {
    
public void desc(){
        System.out.println(
"A");
    }
}

public class ProductB implements IProduct {
    
public void desc(){
        System.out.println(
"B");
    }
}

public class Factory {
    
public static IProduct factory(String name)throws Exception{
        
if(name.equalsIgnoreCase("A")){
            
return new ProductA();
        }
else if(name.equalsIgnoreCase("B")){
            
return new ProductB();
        }
else{
            
throw new Exception("Don't support");
        }
    }
}
优点
1. 工厂创建的类实现相同的接口。便于统一创建和返回。
2. 对于不支持的类型,可以抛出异常。
缺点
1. 不支持新加类型。如果要加入新的类型。需要修改Factory类。
posted on 2011-05-27 10:38 思无 阅读(167) 评论(0)  编辑  收藏 所属分类: 模式

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


网站导航: