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);

}

}


设计原则
依赖抽象,不要依赖具体的抽象.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值