public interface CPU { } public class AmdCPU implements CPU{ public AmdCPU() { System.out.println("this is AmdCPU"); } } public class IntelCPU implements CPU{ public IntelCPU() { System.out.println("this is IntelCPU"); } }
public interface HardDisk { } public class SeagateHardDisk implements HardDisk { public SeagateHardDisk() { System.out.println("this is SeagateHardDisk"); } } public class WdHardDisk implements HardDisk { public WdHardDisk() { System.out.println("this is WdHardDisk"); } }
public interface ComputerFactory { /** * 查看CPU * @return CPU信息 */ CPU viewCPU(); /** * 查看硬盘 * @return 硬盘信息 */ HardDisk viewHardDisk(); } public class DellComputerFactory implements ComputerFactory { @Override public CPU viewCPU() { return new IntelCPU(); } @Override public HardDisk viewHardDisk() { return new SeagateHardDisk(); } } public class LenovoComputerFactory implements ComputerFactory { @Override public CPU viewCPU() { return new AmdCPU(); } @Override public HardDisk viewHardDisk() { return new WdHardDisk(); } }
public class Client { public static void main(String[] args) { ComputerFactory computer = new DellComputerFactory(); computer.viewCPU(); computer.viewHardDisk(); computer = new LenovoComputerFactory(); computer.viewCPU(); computer.viewHardDisk(); } }
输出
this is IntelCPU this is SeagateHardDisk this is AmdCPU this is WdHardDisk