WEB开发网
开发学院软件开发Java hand first 设计模式 - 抽象工厂模式 阅读

hand first 设计模式 - 抽象工厂模式

 2009-09-17 00:00:00 来源:WEB开发网   
核心提示:抽象工厂模式定义提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类. 零件工厂接口 Java代码publicinterfacePartFactory{publicWindowcreateWindow();publicGlasscreateGlass();}零件接口类,让对象更加抽象化 Java代码pub

抽象工厂模式定义提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类.

零件工厂接口

Java代码   

public interface PartFactory { 
 
 public Window createWindow(); 
 
 public Glass createGlass(); 
 
}

零件接口类,让对象更加抽象化

Java代码   

public interface Product { 
 public String name(); 
}

零件-窗

Java代码   

public interface Window extends Product { 
 
}

零件-玻璃

Java代码   

public interface Glass extends Product{ 
 
}

A工厂生产的玻璃

Java代码   

public class AGlass implements Glass { 
 
 @Override 
 public String name() { 
 // TODO Auto-generated method stub 
 return "it is a factory glass"; 
 } 
 
}

A工厂生产的窗

Java代码   

public class AWindow implements Window { 
 
 public String name(){ 
 return "it is a factory window"; 
 } 
 
}

B工厂生产的玻璃

Java代码   

public class BGlass implements Glass { 
 
 @Override 
 public String name() { 
 // TODO Auto-generated method stub 
 return "it is b factory glass"; 
 } 
 
}

B工厂生产的窗

Java代码   

public class BWindow implements Window { 
 
 @Override 
 public String name() { 
 // TODO Auto-generated method stub 
 return "it is b factory window"; 
 } 
 
}

A工厂

Java代码   

public class APartFactory implements PartFactory { 
 
 @Override 
 public Glass createGlass() { 
 // TODO Auto-generated method stub 
 return new AGlass(); 
 } 
 
 @Override 
 public Window createWindow() { 
 // TODO Auto-generated method stub 
 return new AWindow(); 
 } 
 
}

B工厂

Java代码   

public class BPartFactory implements PartFactory { 
 
 @Override 
 public Glass createGlass() { 
 // TODO Auto-generated method stub 
 return new BGlass(); 
 } 
 
 @Override 
 public Window createWindow() { 
 // TODO Auto-generated method stub 
 return new BWindow(); 
 } 
 
}

房子

Java代码   

public class House { 
 
 private Window window; 
 
 private Glass glass; 
 
 public House(Window window,Glass glass){ 
 this.glass = glass; 
 this.window = window; 
 } 
 
 @Override 
 public String toString() { 
 // TODO Auto-generated method stub 
 return window.name()+" / "+ glass.name(); 
 } 
 
 
 
}

测试类

Java代码  

public class Test { 
 
 /** 
 * @param args 
 */ 
 public static void main(String[] args) { 
 // TODO Auto-generated method stub 
 PartFactory aFactory = new APartFactory(); 
  
 PartFactory bFactory = new BPartFactory(); 
 //A工厂零件房子 
 House ahouse = new House(aFactory.createWindow(),aFactory.createGlass()); 
 //B工厂零件房子 
 House bhouse = new House(bFactory.createWindow(),bFactory.createGlass()); 
  
 System.out.println(ahouse); 
  
 System.out.println(bhouse); 
 
 } 
 
}

设计原则

依赖抽象,不要依赖具体的抽象.

Tags:hand first 设计模式

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接