工厂方法模式和抽象工厂
// 抽象产品接口 - Chair
interface Chair {
void sitOn();
}
// 抽象产品接口 - Table
interface Table {
void placeOn();
}
// 具体产品 - Victorian Chair
class VictorianChair implements Chair {
@Override
public void sitOn() {
System.out.println("Sitting on a Victorian chair.");
}
}
// 具体产品 - Modern Chair
class ModernChair implements Chair {
@Override
public void sitOn() {
System.out.println("Sitting on a modern chair.");
}
}
// 具体产品 - Victorian Table
class VictorianTable implements Table {
@Override
public void placeOn() {
System.out.println("Placing on a Victorian table.");
}
}
// 具体产品 - Modern Table
class ModernTable implements Table {
@Override
public void placeOn() {
System.out.println("Placing on a modern table.");
}
}
// 抽象工厂接口
interface FurnitureFactory {
Chair createChair();
Table createTable();
}
// 具体工厂 - Victorian Furniture Factory
class VictorianFurnitureFactory implements FurnitureFactory {
@Override
public Chair createChair() {
return new VictorianChair();
}
@Override
public Table createTable() {
return new VictorianTable();
}
}
// 具体工厂 - Modern Furniture Factory
class ModernFurnitureFactory implements FurnitureFactory {
@Override
public Chair createChair() {
return new ModernChair();
}
@Override
public Table createTable() {
return new ModernTable();
}
}