用抽象工厂模式实现服装工厂类。
时间: 2024-05-03 13:19:24 浏览: 92
抽象工厂模式是一种创建型设计模式,用于创建一组相关或依赖对象而无需指定其具体类。在服装工厂类中,我们可以使用抽象工厂模式来创建不同种类的服装。
首先,我们需要定义一个抽象的服装工厂类,其中包含创建不同种类服装的抽象方法:
```java
public abstract class ClothingFactory {
public abstract Shirt createShirt();
public abstract Pants createPants();
}
```
然后,我们需要定义具体的服装工厂类,这些工厂类将实现抽象工厂类中的方法以创建具体的服装:
```java
public class WinterClothingFactory extends ClothingFactory {
@Override
public Shirt createShirt() {
return new WinterShirt();
}
@Override
public Pants createPants() {
return new WinterPants();
}
}
public class SummerClothingFactory extends ClothingFactory {
@Override
public Shirt createShirt() {
return new SummerShirt();
}
@Override
public Pants createPants() {
return new SummerPants();
}
}
```
最后,我们需要定义具体的服装类,这些类将由具体的工厂类创建:
```java
public abstract class Shirt {
public abstract void wear();
}
public class WinterShirt extends Shirt {
@Override
public void wear() {
System.out.println("穿上了冬款衬衫");
}
}
public class SummerShirt extends Shirt {
@Override
public void wear() {
System.out.println("穿上了夏款衬衫");
}
}
public abstract class Pants {
public abstract void wear();
}
public class WinterPants extends Pants {
@Override
public void wear() {
System.out.println("穿上了冬款裤子");
}
}
public class SummerPants extends Pants {
@Override
public void wear() {
System.out.println("穿上了夏款裤子");
}
}
```
现在,我们可以使用具体的工厂类来创建不同种类的服装:
```java
ClothingFactory winterFactory = new WinterClothingFactory();
Shirt winterShirt = winterFactory.createShirt();
Pants winterPants = winterFactory.createPants();
winterShirt.wear();
winterPants.wear();
ClothingFactory summerFactory = new SummerClothingFactory();
Shirt summerShirt = summerFactory.createShirt();
Pants summerPants = summerFactory.createPants();
summerShirt.wear();
summerPants.wear();
```
输出结果:
```
穿上了冬款衬衫
穿上了冬款裤子
穿上了夏款衬衫
穿上了夏款裤子
```
阅读全文