1、ICPU.java 接口,定义公共方法Calculate
- package cn.javass.dp.abstractfactory.example1;
- /**
- * CPU的接口
- */
- public interface ICPU
- {
- /**
- * 示意方法,CPU具有运算的功能
- */
- public void Calculate();
- }
2、详细CPU类
IntelCPU.java
- package cn.javass.dp.abstractfactory.example1;
- /**
- * Intel的CPU实现
- */
- public class IntelCPU implements ICPU
- {
- /**
- * CPU的针脚数目
- */
- private int pins = 0;
- /**
- * 构造方法,传入CPU的针脚数目
- * @param pins
- * CPU的针脚数目
- */
- public IntelCPU(int pins)
- {
- this.pins = pins;
- }
- public void Calculate()
- {
- System.out.println("now in Intel CPU,pins=" + pins);
- }
- }
AMDCPU.java
- package cn.javass.dp.abstractfactory.example1;
- /**
- * AMD的CPU实现
- */
- public class AMDCPU implements ICPU
- {
- /**
- * CPU的针脚数目
- */
- private int pins = 0;
- /**
- * 构造方法,传入CPU的针脚数目
- *
- * @param pins
- * CPU的针脚数目
- */
- public AMDCPU(int pins)
- {
- this.pins = pins;
- }
- public void Calculate()
- {
- System.out.println("now in AMD CPU,pins=" + pins);
- }
- }
3、CPU工厂类
CPUFactory.java
- package cn.javass.dp.abstractfactory.example1;
- /**
- * 创建CPU的简单工厂
- */
- public class CPUFactory
- {
- /**
- * 创建CPU接口对象的方法
- *
- * @param type
- * 选择CPU类型的参数
- * @return CPU接口对象的方法
- */
- public static ICPU CreateCPU(int type)
- {
- ICPU cpu = null;
- // 根据参数来选择并创建相应的CPU对象
- if (type == CpuType.INTEL)
- {
- cpu = new IntelCPU(1156);
- } else if (type == CpuType.AMD)
- {
- cpu = new AMDCPU(939);
- }
- return cpu;
- }
- }
4、工具、client类
CpuType.java
- package cn.javass.dp.abstractfactory.example1;
- public class CpuType
- {
- public static int INTEL = 1;
- public static int AMD = 2;
- }
Client.java
- package cn.javass.dp.abstractfactory.example1;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- public class Client
- {
- public static void main(String[] args) throws IOException
- {
- int cpuType = 0;
- ICPU cpu = null;
- System.out.print("Starting ....... \n");
-
- for(;;)
- {
- InputStreamReader isr=new InputStreamReader(System.in);
- BufferedReader br=new BufferedReader(isr);
- //if(br.readLine().equalsIgnoreCase(""))
- // continue;
-
- cpuType = Integer.parseInt(br.readLine());
- if(cpuType == CpuType.AMD)
- {
- cpu = CPUFactory.CreateCPU(cpuType);
- cpu.Calculate();
- System.out.print("--------------------------------------\n");
- }
-
- if(cpuType == CpuType.INTEL)
- {
- cpu = CPUFactory.CreateCPU(cpuType);
- cpu.Calculate();
- System.out.print("--------------------------------------\n");
- }
- }
-
- }
- }
参考文献:
《研磨设计模式》王斌、陈臣