写完了工厂模式后,继续学习看书,书上讲到了抽象工厂模式,其实看完书,敲了一篇代码后,感觉还是没有怎么理解它,想通过与前面的工厂模式进行对比学习,但是发现前面的工厂模式学了太久忘记了,尴尬,知识这东西忘记的太快了,写下我对抽象工厂模式的学习记录。
简单来讲抽象工厂,产品接口,然后抽象类实现产品接口,具体类继承抽象类。工厂的话,实现一个接口工厂,具体实现多个具体工厂。
产品接口:
public interface Human {
public void getColor();
public void talk();
public void getSex();
}
产品类抽象类
public abstract class AbstractBlackHuman implements Human {
@Override
public void getColor() {
System.out.println("黑色");
}
@Override
public void talk() {
System.out.println("黑色");
}
}
public abstract class AbstractWhiteHuman implements Human {
@Override
public void getColor() {
System.out.println("白色");
}
@Override
public void talk() {
System.out.println("白色");
}
}
public abstract class AbstractYellowHuman implements Human {
@Override
public void getColor() {
System.out.println("黄色");
}
@Override
public void talk() {
System.out.println("黄色");
}
}
抽象类的实现(具体类)
public class FemaleBlackHuman extends AbstractBlackHuman {
@Override
public void getSex() {
System.out.println("女");
}
}
public class FemalewhiteHuman extends AbstractWhiteHuman {
@Override
public void getSex() {
System.out.println("女");
}
}
public class FemaleYellowHuman extends AbstractYellowHuman {
@Override
public void getSex() {
System.out.println("女");
}
}
public class MaleBlackHuman extends AbstractBlackHuman {
@Override
public void getSex() {
System.out.println("男");
}
}
public class MaleWhiteHuman extends AbstractWhiteHuman {
@Override
public void getSex() {
System.out.println("男");
}
}
public class MaleYellowHuman extends AbstractYellowHuman {
@Override
public void getSex() {
System.out.println("男");
}
}
工厂类的实现(先定义接口,根据不同的性别实现不同的工厂):
工厂接口:
public interface HumanFactory {
public Human createYellowHuman();
public Human createWhiteHuman();
public Human createBlackHuman();
}
女性工厂
public class FemaleFactory implements HumanFactory {
@Override
public Human createYellowHuman() {
return new FemaleYellowHuman();
}
@Override
public Human createWhiteHuman() {
return new FemalewhiteHuman();
}
@Override
public Human createBlackHuman() {
return new FemaleBlackHuman();
}
}
男性工厂
public class FemaleFactory implements HumanFactory {
@Override
public Human createYellowHuman() {
return new FemaleYellowHuman();
}
@Override
public Human createWhiteHuman() {
return new FemalewhiteHuman();
}
@Override
public Human createBlackHuman() {
return new FemaleBlackHuman();
}
}