Cirry's Blog

反射与工厂模式设计

2019-10-15
技术
java
最后更新:2024-03-22
2分钟
384字

反射与工厂模式设计

1
package cn.cccc.demo;
2
import java.lang.reflect.InvocationTargetException;
3
interface IService{
4
public void service();
5
}
6
class HouseService implements IService{
7
@Override
8
public void service() {
9
System.out.println("【服务】:为您的住宿提供服务");
10
}
11
}
12
interface IMessage{
13
public void send();
14
}
15
class CloudMessage implements IMessage{
35 collapsed lines
16
@Override
17
public void send() {
18
// TODO Auto-generated method stub
19
System.out.println("[消息]:发送一个云消息");
20
}
21
}
22
class Factory{
23
private Factory(){} //没有产生实例化对象,所以构造对象私有化
24
@SuppressWarnings("unchecked")
25
26
/**
27
* 获取接口实例化对象,利用泛型去传值很重要
28
* @param className 接口的子类
29
* @param clazz 描述的是一个接口的类型
30
* @return 如果子类存在则返回接口实例化对象
31
*/
32
public static <T> T getInstance(String className, Class<T> clazz){
33
T instance = null;
34
try {
35
instance = (T)Class.forName(className).getDeclaredConstructor().newInstance();
36
} catch (Exception e) {
37
e.printStackTrace();
38
}
39
return instance;
40
}
41
}
42
public class Demo {
43
public static void main(String[] args) throws Exception {
44
IMessage msg = Factory.getInstance("cn.cccc.demo.CloudMessage", IMessage.class);
45
msg.send();
46
IService ser = Factory.getInstance("cn.cccc.demo.HouseService", IService.class);
47
ser.service();
48
49
}
50
}

反射与单例设计模式

1
package cn.cccc.demo;
2
class Singleton{
3
// 这里必须设置volatile 这样可以让其他线程的单例与主线程保持同步
4
private static volatile Singleton instance = null;
5
private Singleton(){
6
System.out.println("*****"+Thread.currentThread().getName()+"实例化Singleton*****");
7
}
8
// 不能给方法设置synchorized,这样的话会卡住其他线程只让一个线程进来
9
public static Singleton getInstance(){
10
if(instance == null){
11
// 这样所有线程都可以不阻塞的进来,但是必须在里面重新判断instance是否为空
12
synchronized (Singleton.class) {
13
if(instance == null ){
14
instance = new Singleton();
15
}
19 collapsed lines
16
}
17
}
18
return instance;
19
}
20
21
public void print(){
22
System.out.println("www.ccc.cn");
23
}
24
}
25
public class Demo {
26
public static void main(String[] args) throws Exception {
27
for(int x =0; x < 3; x++){
28
new Thread(()->{
29
Singleton.getInstance().print();
30
},"单例消费端"+x).start();
31
}
32
33
}
34
}
本文标题:反射与工厂模式设计
文章作者:Cirry
发布时间:2019-10-15
版权声明:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
感谢大佬送来的咖啡☕
alipayQRCode
wechatQRCode