Java 反射 -- 工厂模式的演变

准备些接口和类

public interface IMessage {
    void send();
}

public class NetMessage implements IMessage {
    @Override
    public void send() {
        System.out.println("由网络发送消息");
    }
}

public class QueueMessage implements IMessage {
    @Override
    public void send() {
        System.out.println("由消息队列发送消息");
    }
}

public interface ISay {
    void say();
}

public class Duck implements ISay {
    @Override
    public void say() {
        System.out.println("鸭子呱呱叫");
    }
}

接口直接实例化

public class JavaDemo {
    public static void main(String[] args) throws ClassNotFoundException {
        IMessage message = new NetMessage();
        message.send();
    }
}

弊端:IMessage接口 与 NetMessage子类耦合

静态工厂类

public class Factory {
    private static IMessage message = null;

    private Factory(){}

    public static IMessage getInstance(String className){
        if("NetMessage".equals(className)){
            message = new NetMessage();
        }else if("QueueMessage".equals(className)){
            message = new QueueMessage();
        }
        return message;
    }
}

public class JavaDemo {
    public static void main(String[] args) throws ClassNotFoundException {
        IMessage message = Factory.getInstance("QueueMessage");
        message.send();
    }
}

弊端:当一个接口每多了一个子类,就需要在工厂类中添加一个对应的分支,不符合开闭原则(对于扩展是开放的,对于修改是关闭的)

为一个接口服务的工厂类(反射)

public class Factory {

    private Factory(){}

    public static IMessage getInstance(String className) {
        IMessage instance = null;
        try {
            instance = (IMessage) Class.forName(className).newInstance();
        } catch(Exception e){
            e.printStackTrace();
        }
        return instance;
    }
}

public class JavaDemo {
    public static void main(String[] args) throws Exception {
        IMessage message = Factory.getInstance("com.sheldon.demo.NetMessage");
        message.send();
    }
}

考虑:如果项目中有很多接口,是不是需要写很过工厂类或者方法啊?

为所有接口服务的工厂类(反射 + 泛型)

public class Factory {

    private Factory(){}

    public static  T getInstance(String className,Class cls) {
        T instance = null;
        try {
            instance = (T) Class.forName(className).newInstance();
        } catch(Exception e){
            e.printStackTrace();
        }
        return instance;
    }
}

public class JavaDemo {
    public static void main(String[] args) throws Exception {
        IMessage message = Factory.getInstance("com.sheldon.demo.NetMessage",IMessage.class);
        message.send();
        ISay duck = Factory.getInstance("com.sheldon.demo.Duck",ISay.class);
        duck.say();
    }
}

你可能感兴趣的:(Java 反射 -- 工厂模式的演变)