《研磨设计模式》chap20 享元模式 Flyweight (3)重写应用场景
生活随笔
收集整理的這篇文章主要介紹了
《研磨设计模式》chap20 享元模式 Flyweight (3)重写应用场景
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
public interface Flyweight {//判斷傳入的安全實(shí)體和權(quán)限,是否和享元對象內(nèi)部狀態(tài)匹配 public boolean match(String securityEntity,String permit);
}public class FlyweightFactory {private static FlyweightFactory factory = new FlyweightFactory();private FlyweightFactory(){ }public static FlyweightFactory getInstance(){return factory;}//緩存多個(gè)flyweight對象 private Map<String,Flyweight> fsMap = new HashMap<String,Flyweight>();//獲取key對應(yīng)的享元對象 public Flyweight getFlyweight(String key) {Flyweight f = fsMap.get(key); if(f==null){ //換一個(gè)更簡單點(diǎn)的寫法f = new AuthorizationFlyweight(key);fsMap.put(key,f);}return f;}
}public class SecurityMgr {private static SecurityMgr securityMgr = new SecurityMgr();private SecurityMgr(){ }public static SecurityMgr getInstance(){return securityMgr;} //在運(yùn)行期間,用來存放登錄人員對應(yīng)的權(quán)限,//在Web應(yīng)用中,這些數(shù)據(jù)通常會存放到session中 private Map<String,Collection<Flyweight>> map = new HashMap<String,Collection<Flyweight>>();//模擬登錄的功能 public void login(String user){//登錄的時(shí)候就需要把該用戶所擁有的權(quán)限,從數(shù)據(jù)庫中取出來,放到緩存中去Collection<Flyweight> col = queryByUser(user);map.put(user, col);}//判斷某用戶對某個(gè)安全實(shí)體是否擁有某權(quán)限 public boolean hasPermit(String user,String securityEntity,String permit){Collection<Flyweight> col = map.get(user);if(col==null || col.size()==0){System.out.println(user+"沒有登錄或是沒有被分配任何權(quán)限");return false;}for(Flyweight fm : col){//輸出當(dāng)前實(shí)例,看看是否同一個(gè)實(shí)例對象System.out.println("fm=="+fm);if(fm.match(securityEntity, permit)){return true;}}return false;}//從數(shù)據(jù)庫中獲取某人所擁有的權(quán)限 private Collection<Flyweight> queryByUser(String user){Collection<Flyweight> col = new ArrayList<Flyweight>(); for(String s : TestDB.colDB){String ss[] = s.split(",");if(ss[0].equals(user)){Flyweight fm = FlyweightFactory.getInstance().getFlyweight(ss[1]+","+ss[2]); col.add(fm);}}return col;}
}public static void main(String[] args) throws Exception{//需要先登錄,然后再判斷是否有權(quán)限SecurityMgr mgr = SecurityMgr.getInstance();mgr.login("張三");mgr.login("李四"); boolean f1 = mgr.hasPermit("張三","薪資數(shù)據(jù)","查看");boolean f2 = mgr.hasPermit("李四","薪資數(shù)據(jù)","查看"); System.out.println("f1=="+f1);System.out.println("f2=="+f2); for(int i=0;i<3;i++){mgr.login("張三"+i);mgr.hasPermit("張三"+i,"薪資數(shù)據(jù)","查看");}}
總結(jié)
以上是生活随笔為你收集整理的《研磨设计模式》chap20 享元模式 Flyweight (3)重写应用场景的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《研磨设计模式》chap20 享元模式
- 下一篇: 《研磨设计模式》chap20 享元模式