设计模式 - 抽象工厂模式
Posted 小小程序员的梦想
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式 - 抽象工厂模式相关的知识,希望对你有一定的参考价值。
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
以上是关于设计模式 - 抽象工厂模式的主要内容,如果未能解决你的问题,请参考以下文章