design pattern -- factory

东门清夷
2023-12-01

definition

Define an interface for creating an object but let subclasses decide which class to instantiate. Factory Mehtod lets a class defer instantiation to subclasses.

example

IHumanFactory.java

public interface IHumanFactory {
    public <T extends IHuman> T createHuman(Class c);
}

IHuman.java

public interface IHuman {
    public void talk();
}

HumanFactory.java

public class HumanFactory implements IHumanFactory {

    @Override
    public <T extends IHuman> T createHuman(Class c) {
        // TODO Auto-generated method stub
        IHuman human = null;
        try {
            human = (IHuman)Class.forName(c.getName()).newInstance();
        } catch (Exception e) {
            System.out.println("create human error");
            e.printStackTrace();
        }

        return (T)human;
    }
}

WhiteHuman.java

public class WhiteHuman implements IHuman {

    public void getColor() {
        System.out.println("White human has black skin.");
    }

    public void talk() {
        System.out.println("White human talk.");
    }
}

BlackHuman.java

public class BlackHuman implements IHuman {

    @Override
    public void getColor() {
        // TODO Auto-generated method stub
        System.out.println("Black human has black shin");

    }

    @Override
    public void talk() {
        // TODO Auto-generated method stub
        System.out.println("Black human talk");
    }

}

YellowHuman.java

public class YellowHuman implements IHuman {

    @Override
    public void getColor() {
        // TODO Auto-generated method stub
        System.out.println("Yellow human has yellow skin");
    }

    @Override
    public void talk() {
        // TODO Auto-generated method stub
        System.out.println("Yellow human talk");
    }

}

HumanFactoryTest.java

public class HumanFactoryTest {

    @Test
    public void testCreateHuman() {
        IHumanFactory factory = new HumanFactory();
        IHuman whiteHuman = factory.createHuman(WhiteHuman.class);
        IHuman blackHuman = factory.createHuman(BlackHuman.class);
        IHuman yellowHuman = factory.createHuman(YellowHuman.class);
        whiteHuman.talk();
        blackHuman.talk();
        yellowHuman.talk();
    }
}
 类似资料: