设计模式之工厂模式
1.接口类Human
public interface Human { void getColor(); void talk(); }
2.实现类
/** * black human */ public class BlackHuman implements Human { @Override public void getColor() { System.out.println("黑人"); } @Override public void talk() { System.out.println("黑人, Hello"); } } public class WhiteHuman implements Human { @Override public void getColor() { System.out.println("白种人"); } @Override public void talk() { System.out.println("白种人, hello"); } } public class YellowHuman implements Human { @Override public void getColor() { System.out.println("黄种人"); } @Override public void talk() { System.out.println("黄种人,hello"); } }
3.抽象工厂类
package com.example.demo.entity; public abstract class AbstractHumanFactory { public abstract <T extends Human> T createHuman(Class <T> c); }
4.实现工厂类
package com.example.demo.entity; public class HumanFactory extends AbstractHumanFactory { @Override public <T extends Human> T createHuman(Class<T> c) { //定义一个生产的人种 Human human =null; try { human = (T)Class.forName(c.getName()).newInstance(); }catch (Exception e){ System.out.println("人种生成错误!"); } return (T)human; } }
5.场景类
package com.example.demo.entity; public class NvWa { public static void main(String[] args) { AbstractHumanFactory humanFactory = new HumanFactory(); YellowHuman human = humanFactory.createHuman(YellowHuman.class); human.getColor(); human.talk(); } }