软件设计 石家庄铁道大学信息学院
实验4:抽象工厂模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解抽象工厂模式的动机,掌握该模式的结构;
2、能够利用抽象工厂模式解决实际问题。
[实验任务一]:人与肤色
使用抽象工厂模式,完成下述产品等级结构:
实验要求:
1. 画出对应的类图;
2. 提交源代码;
BlackFactory
package abstractFactory;
public class BlackFactory extends Factory {
@Override
public Man produceMan() {
return new BlackMan();
}
@Override
public Woman produceWoman() {
return new BlackWoman();
}
}
BlackMan
package abstractFactory;
public class BlackMan extends Man{
@Override
public void manProduce() {
System.out.println("生产一个黑色皮肤男人");
}
}
BlackWoman
package abstractFactory;
public class BlackWoman extends Woman{
@Override
public void womanProduce() {
System.out.println("生产一个黑色皮肤的女人");
}
}
Client
package abstractFactory;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
System.out.println("请选择生产的人种:1:黄皮肤男人、2:黄皮肤女人、3:黑皮肤男人、4:黑皮肤女人、5:白皮肤男人、6:白皮肤女人");
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
Factory factory;
Man man;
Woman woman;
if(choice == 1) {
factory = new YellowFactory();
man = factory.produceMan();
man.manProduce();
} else if (choice == 2) {
factory = new YellowFactory();
woman = factory.produceWoman();
woman.womanProduce();
}else if (choice == 3){
factory = new BlackFactory();
man = factory.produceMan();
man.manProduce();
}else if (choice == 4){
factory = new BlackFactory();
woman = factory.produceWoman();
woman.womanProduce();
}else if (choice == 5){
factory = new WhiteFactory();
man = factory.produceMan();
man.manProduce();
}else if(choice == 6){
factory = new WhiteFactory();
woman = factory.produceWoman();
woman.womanProduce();
}
}
}
Factory
package abstractFactory;
public abstract class Factory {
public abstract Man produceMan();
public abstract Woman produceWoman();
}
Man
package abstractFactory;
public abstract class Man {
public abstract void manProduce();
}
WhiteFactory
package abstractFactory;
public class WhiteFactory extends Factory{
@Override
public Man produceMan() {
return new WhiteMan();
}
@Override
public Woman produceWoman() {
return new WhiteWoman();
}
}
WhiteMan
package abstractFactory;
public class WhiteMan extends Man{
@Override
public void manProduce() {
System.out.println("生产一个白色皮肤男人");
}
}
WhiteWoman
package abstractFactory;
public class WhiteWoman extends Woman{
@Override
public void womanProduce() {
System.out.println("生产一个白色皮肤的女人");
}
}
Woman
package abstractFactory;
public abstract class Woman {
public abstract void womanProduce();
}
YellowFactory
package abstractFactory;
public class YellowFactory extends Factory{
@Override
public Man produceMan() {
return new YellowMan();
}
@Override
public Woman produceWoman() {
return new YellowWoman();
}
}
YellowMan
package abstractFactory;
public class YellowMan extends Man{
@Override
public void manProduce() {
System.out.println("生产一个黄色皮肤男人");
}
}
YellowWoman
package abstractFactory;
public class YellowWoman extends Woman{
@Override
public void womanProduce() {
System.out.println("生产一个黄色皮肤的女人");
}
}