设计模式之抽象工厂模式

接上文 工厂方法模式

    很多读者读完工厂方法模式,认为这很不错,不过你能看出它明显的弊端吗,需求总是变换的,工厂方法模式,抽象工厂里面有个生产实例的方法。对于一种良好的模式,工厂方法模式中,一种产品应该对应一个抽象工厂,那么你新增一个电脑(computer),你就要新增一个抽象工厂,还要新增一个抽象工厂的的实现类,这很麻烦,关键在于你要新增很多东西,所以麻烦。

    我们可以在一个抽象工厂里面生产所有的抽象产品,比如computer,mobile,让继承抽象工厂的类去创建具体的产品,根据用户需要自己创建。



abstract class Cpu {
    abstract String getName();
}

public class Intel extends Cpu{
	@Override
	String getName() {
		return "奔腾4 3.2C";
	}
}

public class AMD extends Cpu{
	@Override
	String getName() {
		// TODO Auto-generated method stub
		return "Athlon XP 2008+";
	}
}

abstract class HardDisk {
    abstract String getSize();
}

public class WestDigit extends HardDisk{

	@Override
	String getSize() {
		// TODO Auto-generated method stub
		return "WD2500JD 250G";
	}

}

public class Maxtor extends HardDisk{
	@Override
	String getSize() {
		// TODO Auto-generated method stub
		return "MaXLine Plus II 200G";
	}
}

abstract class MainBoard {
    abstract void attach(Cpu cpu) throws Exception;
}

public class MSI865PE extends MainBoard{

	@Override
	void attach(Cpu cpu) throws Exception {
		if(cpu.getClass ().toString ().endsWith("Intel")){
            System.out.println("MSI865PE");
        }
         else{
            throw new Exception("主板MSI865PE只能配Intel的 CPU");
        }
	}

}

public class MSIK7N2G extends MainBoard{
	@Override
	void attach(Cpu cpu) throws Exception {
		if(cpu.getClass().toString().endsWith("Intel")){
			System.out.println("MSIK7N2G");
		}else{
			throw new Exception("主板MSIK7N2G只能配AMD的CPU");
		}
	}
}

public class Ibm extends ComputerFactory{
    Ibm(){
    	cpu = new Intel();
    	hardDisk = new WestDigit();
    	mainBoard = new MSI865PE();
    }
}

public class Dell extends ComputerFactory{
    Dell(){
    	cpu = new AMD();
    	hardDisk = new Maxtor();
    	mainBoard = new MSIK7N2G();
    }
}


public class Client {
    public static void main(String[] args) throws Exception{
    	Ibm ibm = new Ibm();
    	ibm.show();
    }
}


自己体会这种设计的好处,比如,可以根据需要创建IBM或者Dell的工厂,每个工厂都能生产多种产品,无论你新加产品还是新加工厂,只需增加类即可,而且每个工厂都有不同的组合方式,真是太过瘾了。。。未完待续




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值