抽象工厂模式——java实现

使用抽象工厂模式,完成下述产品等级结构:

类图:

 

java代码:

抽象工厂类——AbstractFactory类:
package com.shiyan4;
public interface AbstractFactory {
    public Man produceMan();
    public Woman produceWoman();
} 

具体工厂类——YellowFactory类:
public class YellowFactory implements AbstractFactory{
    public Man produceMan()
    {
        return new YellowMan();
    }
    public Woman produceWoman()
    {
        return new YellowWoman();
    }
}
具体工厂类——BlackFactory类:
public class BlackFactory implements AbstractFactory{
    public Man produceMan()
    {
        return new BlackMan();
    }
    public Woman produceWoman()
    {
        return new BlackWoman();
    }
} 
具体工厂类——WhiteFactory类:
public class WhiteFactory implements AbstractFactory{
    public Man produceMan()
    {
        return new WhiteMan();
    }
    public Woman produceWoman()
    {
        return new WWoman();
    }
}
抽象产品类——Man类:
public interface Man {
    public void show();
} 
抽象产品类——Woman类:
public interface Woman {
    public void show();
} 
具体产品类——YellowMan类:
public class YellowMan implements Man{
    public void show()
    {
        System.out.println("黄皮肤的男性");
    }
}
具体产品类——BlackMan类:
public class BlackMan implements Man{
    public void show()
    {
        System.out.println("黑皮肤的男性");
    }
} 
具体产品类——WhiteMan类:
public class WhiteMan implements Man{
    public void show()
    {
        System.out.println("白皮肤的男性");
    }
} 
具体产品类——YellowWoman类:
public class YellowWoman implements Woman {
    public void show()
    {
        System.out.println("黄皮肤的女性");
    }
} 
具体产品类——BlackWoman类:
public class BlackWoman implements Woman {
    public void show()
    {
        System.out.println("黑皮肤的女性");
    }
} 
具体产品类——WhiteWoman类:
public class WhiteWoman implements Woman {
    public void show()
    {
        System.out.println("白皮肤的女性");
    }
}
测试类——Main类:
public class main {
    public static void main(String args[])
    {
        try
        {
            AbstractFactory fac;
            Man m;
            Woman w;
            fac=new WhiteFactory();
            m=fac.produceMan();
            m.show();
            w=fac.produceWoman();
            w.show();
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
} 

运行结果

 

 

 

 

 

posted @ 2022-09-25 17:04  好(justice)……  阅读(50)  评论(0编辑  收藏  举报