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

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


零件工厂接口
public interface PartFactory {
	
	public Window createWindow();
	
	public Glass createGlass();

}


零件接口类,让对象更加抽象化
public interface Product {
	public String name();
}



零件-窗
public interface Window extends Product {

}


零件-玻璃
public interface Glass extends Product{

}



A工厂生产的玻璃
public class AGlass implements Glass {

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

}


A工厂生产的窗
public class AWindow implements Window {
	
	public String name(){
		return "it is a factory window";
	}
	
}


B工厂生产的玻璃


public class BGlass implements Glass {

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

}


B工厂生产的窗
public class BWindow implements Window {

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

}


A工厂

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工厂
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();
	}

}



房子
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();
	}
	
	

}


测试类
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);

	}

}


设计原则
   依赖抽象,不要依赖具体的抽象.








你可能感兴趣的:(java,设计模式)