- // 抽象产品
- abstract class Human {
- public abstract void Eat();
- public abstract void Sleep();
- public abstract void Beat();
- }
- // 具体产品-男人
- class Man extends Human {
- public void Eat() {
- System.out.println("Man can eat.");
- }
- public void Sleep() {
- System.out.println("Man can sleep.");
- }
- public void Beat() {
- System.out.println("Man can beat doudou.");
- }
- }
- // 具体产品-女人
- class Female extends Human{
- public void Eat() {
- System.out.println("Female can eat.");
- }
- public void Sleep() {
- System.out.println("Female can sleep.");
- }
- public void Beat() {
- System.out.println("Female can beat doudou.");
- }
- }
- // 简单工厂变为了抽象工厂
- abstract class HumanFactory {
- public abstract Human createHuman(String gender) throws IOException;
- }
- // 具体工厂(每个具体工厂负责一个具体产品)
- class ManFactory extends HumanFactory{
- public Human createHuman(String gender) throws IOException {
- return new Man();
- }
- }
- class FemaleFactory extends HumanFactory{
- public Human createHuman(String gender) throws IOException {
- return new Female();
- }
- }
- // 女娲造人
- public class Goddess {
- public static void main(String[] args) throws IOException {
- // 造个男人
- HumanFactory hf = new ManFactory();
- Human h = hf.createHuman("man");
- h.Eat();
- h.Sleep();
- h.Beat();
- }
- }
复制代码 |
|