目录
反射机制优化工厂类
1.先写一个反射的小Demo
2.写一个工厂类使用例子
(1)IMessage只有一个实现类NewsPaper
(2)IMessage添加一个实现类NetReport
反射机制优化工厂类
1.先写一个反射的小Demo
clazz.newInstance();相当于new java.util.Date();得到一个实例对象
package com.liangyehao;
public class Demo01 {
public static void main(String[] args) throws
ClassNotFoundException, IllegalAccessException, InstantiationException {
//获取类对象
Class<?> clazz = Class.forName("java.util.Date");
//反射获得实例对象,相当于 new java.util.Date();
Object object = clazz.newInstance();
//输出实例对象
System.out.println(object);
}
}
2.写一个工厂类使用例子
(1)IMessage只有一个实现类NewsPaper
-
编写一个接口IMessage,定义了send方法
package com.liangyehao.factoryDemo; public interface IMessage { public void send(String msg); }
-
编写IMessage实现类NewsPaper.java
package com.liangyehao.factoryDemo.impl; import com.liangyehao.factoryDemo.IMessage; public class NewsPaper implements IMessage { public void send(String msg) { System.out.println("【报纸内容】"+msg); } }
-
编写工厂类MessageFactory.java
package com.liangyehao.factoryDemo; import com.liangyehao.factoryDemo.impl.NewsPaper; public class MessageFactory { private MessageFactory(){} public static IMessage getInstance(String className){ if("newspaper".equals(className)){ return new NewsPaper(); } return null; } }
-
编写测试类
package com.liangyehao.factoryDemo; public class MessageTest { public static void main(String[] args) { IMessage message = MessageFactory.getInstance("newspaper"); message.send("Hello liangyehao"); } }
-
测试输出
【报纸内容】Hello liangyehao
(2)IMessage添加一个实现类NetReport
-
编写NetReport.java
package com.liangyehao.factoryDemo.impl; import com.liangyehao.factoryDemo.IMessage; public class NetReport implements IMessage{ public void send(String msg) { System.out.println("{网络报道}"+msg); } }
-
工厂类添加实现
package com.liangyehao.factoryDemo; import com.liangyehao.factoryDemo.impl.NetReport; import com.liangyehao.factoryDemo.impl.NewsPaper; public class Factory { public Factory(){} public static IMessage getInstance(String type){ if(type.equals("newspaper")){ return new NewsPaper(); }else if(type.equals("netreport")){ return new NetReport(); } return null; } }
即增加了:
else if(type.equals("netreport")){ return new NetReport(); }
-
测试类测试NetReport
package com.liangyehao.factoryDemo; public class IMessageTest { public static void main(String[] args) { IMessage newsPaper = Factory.getInstance("netreport"); newsPaper.send("Hello liangyehao"); } }
-
输出结果
{网络报道}Hello liangyehao