软件设计 石家庄铁道大学信息学院
实验4:抽象工厂模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解抽象工厂模式的动机,掌握该模式的结构;
2、能够利用抽象工厂模式解决实际问题。
[实验任务一]:人与肤色
使用抽象工厂模式,完成下述产品等级结构:
实验要求:
// 抽象产品类:人
public abstract class Human {
protected
SkinColor skinColor;
public Human(SkinColor
skinColor) {
this.skinColor = skinColor;
}
public SkinColor
getSkinColor() {
return
skinColor;
}
public abstract
void display();
}
// 抽象产品类:肤色
public abstract class SkinColor {
public abstract
void display();
}
// 具体产品类:亚洲人
public class Asian extends Human {
public
Asian(SkinColor skinColor) {
super(skinColor);
}
@Override
public void
display() {
System.out.println("Asian with " + skinColor);
}
}
// 具体产品类:非洲人
public class African extends Human {
public
African(SkinColor skinColor) {
super(skinColor);
}
@Override
public void
display() {
System.out.println("African with " + skinColor);
}
}
// 具体产品类:欧洲人
public class European extends Human {
public
European(SkinColor skinColor) {
super(skinColor);
}
@Override
public void
display() {
System.out.println("European with " + skinColor);
}
}
// 具体产品类:黄色皮肤
public class Yellow extends SkinColor {
@Override
public void
display() {
System.out.println("Yellow Skin");
}
}
// 具体产品类:黑色皮肤
public class Black extends SkinColor {
@Override
public void
display() {
System.out.println("Black Skin");
}
}
// 具体产品类:白色皮肤
public class White extends SkinColor {
@Override
public void
display() {
System.out.println("White Skin");
}
}
// 抽象工厂
public interface HumanFactory {
Human
createHuman();
SkinColor
createSkinColor();
}
// 具体工厂:亚洲人工厂
public class AsianFactory implements HumanFactory {
@Override
public Human
createHuman() {
return new
Asian(createSkinColor());
}
@Override
public SkinColor
createSkinColor() {
return new
Yellow();
}
}
// 具体工厂:非洲人工厂
public class AfricanFactory implements HumanFactory {
@Override
public Human
createHuman() {
return new
African(createSkinColor());
}
@Override
public SkinColor
createSkinColor() {
return new
Black();
}
}
// 具体工厂:欧洲人工厂
public class EuropeanFactory implements HumanFactory {
@Override
public Human
createHuman() {
return new
European(createSkinColor());
}
@Override
public SkinColor
createSkinColor() {
return new
White();
}
}
public class Client {
public static
void main(String[] args) {
HumanFactory
factory = new AsianFactory();
Human human =
factory.createHuman();
human.display();
factory = new
AfricanFactory();
human =
factory.createHuman();
human.display();
factory = new
EuropeanFactory();
human =
factory.createHuman();
human.display();
}
}