宜家(IKEA)和红星麦凯龙(Macalline)都在售卖衣柜(Wardrobe)和沙发(Sofa),请用JAVA控制台应用程序实现这两个家具店经营产品的抽象工厂模式。 要求输出:IKEAWardrobe,IKEASofa,MacallineWardrobe,MacallineSofa
时间: 2024-02-26 07:57:22 浏览: 218
JAVA设计模式之抽象工厂模式案例
好的,我已经理解了你的问题。以下是实现抽象工厂模式的Java代码:
```java
// 抽象家具工厂
interface FurnitureFactory {
Wardrobe createWardrobe();
Sofa createSofa();
}
// 宜家家具工厂
class IKEAFurnitureFactory implements FurnitureFactory {
public Wardrobe createWardrobe() {
return new IKEAWardrobe();
}
public Sofa createSofa() {
return new IKEASofa();
}
}
// 红星麦凯龙家具工厂
class MacallineFurnitureFactory implements FurnitureFactory {
public Wardrobe createWardrobe() {
return new MacallineWardrobe();
}
public Sofa createSofa() {
return new MacallineSofa();
}
}
// 衣柜抽象类
abstract class Wardrobe {
public abstract void show();
}
// 宜家衣柜
class IKEAWardrobe extends Wardrobe {
public void show() {
System.out.println("This is IKEAWardrobe.");
}
}
// 红星麦凯龙衣柜
class MacallineWardrobe extends Wardrobe {
public void show() {
System.out.println("This is MacallineWardrobe.");
}
}
// 沙发抽象类
abstract class Sofa {
public abstract void show();
}
// 宜家沙发
class IKEASofa extends Sofa {
public void show() {
System.out.println("This is IKEASofa.");
}
}
// 红星麦凯龙沙发
class MacallineSofa extends Sofa {
public void show() {
System.out.println("This is MacallineSofa.");
}
}
// 测试程序
public class Test {
public static void main(String[] args) {
FurnitureFactory factory1 = new IKEAFurnitureFactory();
FurnitureFactory factory2 = new MacallineFurnitureFactory();
Wardrobe wardrobe1 = factory1.createWardrobe();
Sofa sofa1 = factory1.createSofa();
Wardrobe wardrobe2 = factory2.createWardrobe();
Sofa sofa2 = factory2.createSofa();
wardrobe1.show(); // 输出:IKEAWardrobe
sofa1.show(); // 输出:IKEASofa
wardrobe2.show(); // 输出:MacallineWardrobe
sofa2.show(); // 输出:MacallineSofa
}
}
```
程序的运行结果为:
```
This is IKEAWardrobe.
This is IKEASofa.
This is MacallineWardrobe.
This is MacallineSofa.
```
以上是实现抽象工厂模式的Java程序,其中抽象工厂接口`FurnitureFactory`定义了两个生产家具的方法`createWardrobe()`和`createSofa()`,分别用来生产衣柜和沙发。然后我们定义了两个具体工厂`IKEAFurnitureFactory`和`MacallineFurnitureFactory`,分别生产宜家和红星麦凯龙的衣柜和沙发。接着定义了衣柜和沙发的抽象类`Wardrobe`和`Sofa`,这两个抽象类分别具有一个`show()`方法,用来展示衣柜和沙发的信息。最后,我们定义了具体的衣柜和沙发类,分别是`IKEAWardrobe`、`MacallineWardrobe`、`IKEASofa`和`MacallineSofa`,它们都是`Wardrobe`或`Sofa`的具体实现类,实现了`show()`方法。在测试程序中,我们分别使用两个具体工厂来生产衣柜和沙发,然后展示它们的信息。
阅读全文