实验4:抽象工厂模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解抽象工厂模式的动机,掌握该模式的结构;

2、能够利用抽象工厂模式解决实际问题

 

[实验任务一]:人与肤色

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

 

实验要求:

1.画出对应的类图;

2.提交源代码;

3.注意编程规范。

1、类图

 

 

2、源代码

AbstractFactory.java

package org.example;

 

public interface AbstractFactory {

    public Man produceMan();

    public Woman produceWoman();

}

 

YellowFactory.java

package org.example;

 

public class YellowFactory implements AbstractFactory{

    public Man produceMan()

    {

        return new YellowMan();

    }

    public Woman produceWoman()

    {

        return new YellowWoman();

    }

}

BlackFactory.java

package org.example;

 

public class BlackFactory implements AbstractFactory{

    public Man produceMan()

    {

        return new BlackMan();

    }

    public Woman produceWoman()

    {

        return new BlackWoman();

    }

}

WhiteFactory.java

package org.example;

 

public class WhiteFactory implements AbstractFactory{
    public Man produceMan()
    {
        return new WhiteMan();
    }
    public Woman produceWoman()
    {
        return new Woman() {
            @Override
            public void show() {

            }
        };
    }
}

Man.java

package org.example;

 

public interface Man {

    public void show();

}

Woman.java

package org.example;

 

public interface Woman {

    public void show();

}

YellowMan.java

package org.example;

 

public class YellowMan implements Man{

    public void show()

    {

        System.out.println("黄皮肤的男性");

    }

}

BlackMan.java

package org.example;

 

public class BlackMan implements Man{

    public void show()

    {

        System.out.println("黑皮肤的男性");

    }

}

WhiteMan.java

package org.example;

 

public class WhiteMan implements Man{

    public void show()

    {

        System.out.println("白皮肤的男性");

    }

}

YellowWoman.java

package org.example;

 

public class YellowWoman implements Woman {

    public void show()

    {

        System.out.println("黄皮肤的女性");

    }

}

BlackWoman.java

package org.example;

 

public class BlackWoman implements Woman {

    public void show()

    {

        System.out.println("黑皮肤的女性");

    }

}

WhiteWoman.java

package org.example;

 

public class WhiteWoman implements Woman {

    public void show()

    {

        System.out.println("白皮肤的女性");

    }

}

Main.java

package org.example;

 

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 @ 2024-10-28 08:58  不会JAVA的小袁  阅读(7)  评论(0编辑  收藏  举报