设计模式-抽象工厂模式(Abstract Factory)

1.一个系统不应当依赖于产品类实例如何被创建、组合和表达的细节,这对于所有形态的工厂模式都是重要的。

2.这个系统的产品有多于一个的产品族,而系统只消费其中某一族的产品。

3.同属于同一个产品族的产品是在一起使用的,这一约束必须在系统的设计中体现出来。(比如:Intel主板必须使用Intel CPU、Intel芯片组)

4.系统提供一个产品类的库,所有的产品以同样的接口出现,从而使客户端不依赖于实现。

Cpu.java

package cn.foxeye.design.abstractfactory;

public interface Cpu {
	
	void getCpuTypeName();

}

 

IntelCpu.java

package cn.foxeye.design.abstractfactory;

public class IntelCpu implements Cpu {

	private String cpuTypeName = "Intel";

	@Override
	public void getCpuTypeName() {
		System.out.println("CPU 型号:" + cpuTypeName);
	}

}

 

AmdCpu.java

package cn.foxeye.design.abstractfactory;

public class AmdCpu implements Cpu {

	private String cpuTypeName = "AMD";

	@Override
	public void getCpuTypeName() {
		System.out.println("CPU 型号:" + cpuTypeName);
	}

}

 

Mainboard.java

package cn.foxeye.design.abstractfactory;

public interface Mainboard {
	
	void getMainboardTypeName();

}

 

IntelMainboard.java

package cn.foxeye.design.abstractfactory;

public class IntelMainboard implements Mainboard {

	private String mainboardTypeName = "Intel";

	@Override
	public void getMainboardTypeName() {
		System.out.println("主板型号:" + mainboardTypeName);
	}

}

AmdMainboard.java

package cn.foxeye.design.abstractfactory;

public class AmdMainboard implements Mainboard {

	private String mainboardTypeName = "AMD";

	@Override
	public void getMainboardTypeName() {
		System.out.println("主板型号:" + mainboardTypeName);
	}

}

 

ComputerFactory.java

package cn.foxeye.design.abstractfactory;

public interface ComputerFactory {
	
	Cpu createCpu();
	
	Mainboard createMainboard();

}

 

IntelComputerFactory.java

package cn.foxeye.design.abstractfactory;

public class IntelComputerFacotry implements ComputerFactory {

	@Override
	public Cpu createCpu() {

		return new IntelCpu();
	}

	@Override
	public Mainboard createMainboard() {
		return new IntelMainboard();
	}

}

 

AmdComputerFactory.java

package cn.foxeye.design.abstractfactory;

public class AmdComputerFacotry implements ComputerFactory {

	@Override
	public Cpu createCpu() {

		return new AmdCpu();
	}

	@Override
	public Mainboard createMainboard() {
		return new AmdMainboard();
	}

}

 

Main.java

package cn.foxeye.design.abstractfactory;

public class Main {

	public static void main(String[] args) {

		ComputerFactory factory = new AmdComputerFacotry();
		
		factory.createCpu().getCpuTypeName();
		factory.createMainboard().getMainboardTypeName();
	}

}

 

参考实例来源于博客特种兵—AK47的《JAVA与模式》26天系列—第3天—抽象工厂模式的文章,仅供自己学习用。

你可能感兴趣的:(设计模式,abstract,抽象工厂模式,Factory模式)