主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式。
例子1
连接池,用的就是享元模式。连接池中放入一些连接对象,使用的时候去连接池中拿连接对象,用完了再放回到连接池中。下面一个简单的连接池例子,主要是演示享元模式,代码本身可能会有一些并发问题,但是不重要,这里不是主要探讨多线程和并发,主要为了演示享元模式,所以这些小问题可以忽略。
package org.garen.flyweight;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* 连接类
*/
class Connection {
private String conStr; // 连接字符串
public Connection(String conStr){
this.conStr = conStr;
}
}
/**
* 连接工厂
*/
class ConnectionFactory {
// 连接池
static Queue<Connection> conPool = new ConcurrentLinkedQueue<>();
// 使用中的连接,放到这个临时的池子中
static Map<Integer, Connection> tmpPool = new ConcurrentHashMap<>();
// 连接池中放入10个连接对象
static {
String conStr = "ip:localhost,userName:root,password:123";
for (int i = 0; i < 10; i++) {
Connection conn = new Connection(conStr);
conPool.add(conn);
}
}
// 获取连接,拿不到连接就等待100ms,允许重试3次,还拿不到就返回null
private static Connection getConn(int count, String threadName) {
Connection conn = null;
if(conPool.isEmpty()){
count ++;
if(count < 3){ // 重试3次
try {
System.out.println(threadName + " is waiting " + count);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
getConn(count, threadName);
}
}else{
conn = conPool.poll();
tmpPool.put(conn.hashCode(), conn);
}
return conn;
}
// 获取连接,拿不到连接就等待100ms,允许重试3次,还拿不到就返回null
static Connection getConn(String threadName) {
return getConn(0, threadName);
}
// 连接用完了,放回连接池
static void closeConn(Connection conn, String threadName) {
if(conn == null) throw new RuntimeException("conn is null");
Connection connection = tmpPool.get(conn.hashCode());
if(connection == null) throw new RuntimeException("conn is not exist");
tmpPool.remove(conn.hashCode());
conPool.add(connection);
System.out.println(threadName + " - " + conn.hashCode() + " close conn.");
}
}
/**
* 测试类
*/
public class Main {
// 创建20个线程,模拟使用连接池
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
new Thread(()-> {
String threadName = Thread.currentThread().getName();
Connection conn = ConnectionFactory.getConn(threadName);
if(conn == null){
System.out.println(threadName + " get conn fail");
}else{
System.out.println(threadName + " - " + conn.hashCode() + " using...");
try {
Thread.sleep(new Random().nextInt(5) * 200);
ConnectionFactory.closeConn(conn, threadName);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
}
运行结果:
Thread-19 - 1142769328 using…
Thread-14 - 1495206255 using…
Thread-15 - 465327489 using…
Thread-18 - 1547999141 using…
Thread-10 - 821828208 using…
Thread-17 - 439689152 using…
Thread-15 - 465327489 close conn.
Thread-13 - 1835885936 using…
Thread-16 - 2069791201 using…
Thread-9 is waiting 1
Thread-4 is waiting 1
Thread-5 is waiting 1
Thread-3 is waiting 1
Thread-2 is waiting 1
Thread-8 is waiting 1
Thread-6 - 465327489 using…
Thread-7 - 821828208 using…
Thread-11 - 94808467 using…
Thread-1 is waiting 1
Thread-0 is waiting 1
Thread-12 - 1109337020 using…
Thread-10 - 821828208 close conn.
Thread-1 is waiting 2
Thread-0 is waiting 2
Thread-3 is waiting 2
Thread-2 is waiting 2
Thread-9 is waiting 2
Thread-4 is waiting 2
Thread-8 is waiting 2
Thread-5 is waiting 2
Thread-19 - 1142769328 close conn.
Thread-7 - 821828208 close conn.
Thread-4 get conn fail
Thread-1 get conn fail
Thread-0 get conn fail
Thread-8 get conn fail
Thread-9 get conn fail
Thread-5 get conn fail
Thread-2 get conn fail
Thread-3 get conn fail
Thread-12 - 1109337020 close conn.
Thread-18 - 1547999141 close conn.
Thread-16 - 2069791201 close conn.
Thread-13 - 1835885936 close conn.
Thread-17 - 439689152 close conn.
Thread-14 - 1495206255 close conn.
Thread-6 - 465327489 close conn.
Thread-11 - 94808467 close conn.
例子2
String类型用的也是享元模式。
package org.garen.flyweight;
public class Main2 {
public static void main(String[] args) {
String s1 = "abc"; // abc在常量池
String s2 = "abc"; // abc在常量池
String s3 = new String("abc");
String s4 = new String("abc");
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s3 == s4);
System.out.println(s3.intern() == s1);
}
}