标签:思想 null override 性能 员工 getc 效率 tco 复杂度
角色 | 作用 |
---|---|
抽象享元 | 定义需共享的对象的业务接口 |
具体享元 | 实现抽象享元接口,完成某一具体逻辑 |
享元工厂 | 创建具体享元类,维护相同的享元对象 |
Main | 通过享元工厂获得享元对象 |
public interface QueryManager {
public String createQuery();
public void setStatus(String status);
}
public class EmployeeQueryManager implements QueryManager {
protected String name; //内部状态
public EmployeeQueryManager(String name){
this.name = name;
}
@Override
public String createQuery() {
return "This is EmployeeQuery : "+name;
}
@Override
public void setStatus(String status) {
System.out.println("Employee Status : " + status); //外部状态
}
}
public class CompanyQueryManager implements QueryManager {
protected String name; //内部状态
public CompanyQueryManager(String name){
this.name = name;
}
@Override
public String createQuery() {
return "This is CompanyQuery : " + name;
}
@Override
public void setStatus(String status) {
System.out.println("Company Status : " + status); //外部状态
}
}
public class QueryManagerFactory {
static Map<String,QueryManager> eqm = new HashMap<String,QueryManager>();
static Map<String,QueryManager> cqm = new HashMap<String,QueryManager>();
public QueryManager getCompanyQueryManager(String name){
QueryManager qm = cqm .get(name);
if(qm==null){
qm = new CompanyQueryManager(name);
cqm.put(name, qm);
}
return qm;
}
public QueryManager getEmployeeQueryManager(String name){
QueryManager qm = eqm .get(name);
if(qm==null){
qm = new EmployeeQueryManager(name);
eqm.put(name, qm);
}
return qm;
}
public static int getCompanySize(){
return cqm.size();
}
public static int getEmployeeSize(){
return eqm.size();
}
}
public class FlyWeightTest {
public static void main(String[] args) {
QueryManagerFactory qmf = new QueryManagerFactory();
QueryManager qma = qmf.getCompanyQueryManager("公司甲");
qma.setStatus("false"); //Company Status : false
QueryManager qm1 = qmf.getEmployeeQueryManager("员工甲");
qm1.setStatus("true"); //Employee Status : true
QueryManager qm2 = qmf.getEmployeeQueryManager("员工乙");
qm2.setStatus("false"); //Employee Status : false
QueryManager qm3 = qmf.getEmployeeQueryManager("员工甲");
qm3.setStatus("false"); //Employee Status : false
System.out.println(qma.createQuery() + "; CompanyQuery size : " + qmf.getCompanySize());
//This is CompanyQuery : 公司甲; CompanyQuery size : 1
System.out.println(qm1.createQuery() + "; EmployeeQuery size : " + qmf.getEmployeeSize());
//This is EmployeeQuery : 员工甲; EmployeeQuery size : 2
System.out.println(qm2.createQuery() + "; EmployeeQuery size : " + qmf.getEmployeeSize());
//This is EmployeeQuery : 员工乙; EmployeeQuery size : 2
System.out.println(qm3.createQuery() + "; EmployeeQuery size : " + qmf.getEmployeeSize());
//This is EmployeeQuery : 员工甲; EmployeeQuery size : 2
}
}
标签:思想 null override 性能 员工 getc 效率 tco 复杂度
原文地址:https://www.cnblogs.com/Ch1nYK/p/9060809.html