抽象工厂代码示例
为创建一组相关或相互依赖的对象提供一个接口,而且无需指定它们的具体类。
产品族需要扩展的不适合抽象工厂,即在抽象工厂中在加一个createXXX();
public class AbstractFactory {
public static void main(String[] args) {
ComputerFactory factory = new Hp();
System.out.println(factory);
System.out.println(factory.createCpu());
System.out.println(factory.createBoard());
System.out.println(factory.createGpu());
}
}
abstract class ComputerFactory {
public abstract Cpu createCpu();
public abstract Board createBoard();
public abstract Gpu createGpu();
@Override
public String toString() {
return this.getClass().getSimpleName();
}
}
class Hp extends ComputerFactory {
@Override
public Cpu createCpu() {
return new Core();
}
@Override
public Board createBoard() {
return new MSI();
}
@Override
public Gpu createGpu() {
return new Nvidia();
}
}
class Mechrevo extends ComputerFactory {
@Override
public Cpu createCpu() {
return new Ryzen();
}
@Override
public Board createBoard() {
return new ASUS();
}
@Override
public Gpu createGpu() {
return new ATI();
}
}
abstract class Cpu {
@Override
public String toString() {
return this.getClass().getSimpleName();
}
}
abstract class Board {
@Override
public String toString() {
return this.getClass().getSimpleName();
}
}
abstract class Gpu {
@Override
public String toString() {
return this.getClass().getSimpleName();
}
}
class Ryzen extends Cpu {
}
class Core extends Cpu {
}
class Nvidia extends Gpu {
}
class ATI extends Gpu {
}
class MSI extends Board {
}
class ASUS extends Board {
}
标签:return,示例,代码,abstract,public,抽象,Override,extends,class
From: https://www.cnblogs.com/annamaple/p/17381828.html