享元模式(Flyweight Pattern)

享元模式(Flyweight Pattern)

享元模式是对象池的一种体现。类似于线程池,可以避免不停地创建和销毁多个对象。实际上就是将多个同一个对象的访问集中起来,类似于数据库连接池。

To illustrate with  a scene of  ticket-grabbing

public interface ITicket {
    void  showInfo(String bunk);
}
public class TrainTicket implements ITicket {

    private String from;
    private String destination;
    private int price;
    TrainTicket(String from, String destination) {
        this.from = from;
        this.destination = destination;
    }


    // get information from website of 12306 or someone else
    @Override
    public void showInfo(String bunk) {
        this.price= new Random().nextInt(500);
        System.out.println(from+"->"+destination+":"+bunk+" price:"+this.price);
    }
}

the duty of Method named showInfo is to get infromation of ticket form other places,whcih will consume many performance of computer and  time.when we get a information we will  assemble them into an instance,we should make a same instance just be cerate once.

public class TicketFactory {
    static Map<String, ITicket> pool = new ConcurrentHashMap();
    static ITicket query(String from,String destination){
        String key=from+"->"+destination;
        if (pool.containsKey(key)){
            System.out.println("use cache ");
            return pool.get(key);
        }
        System.out.println("first query and create instance: "+key);
        ITicket iTicket=new TrainTicket(from,destination);
        pool.put(key,iTicket);
        return iTicket;
    }
}

 To test

public class Test {
    public static void main(String[] args) {
        ITicket query = TicketFactory.query("beijing", "xian");
        query.showInfo("hard seat");
        query = TicketFactory.query("beijing", "xian");
        query.showInfo("soft seat");

    }
}

 

 To expalin

we query the same place of departure and destination,the first time we go to website named 12306 to get infromation ,but the second time we just get message from cache, so that we do not have to spent much time and consume performance of computer

 

tips:

you may have a question of that is it similiar with pattern of register singleton!you can see it again,actually, it bit like that but the dimension of  Register Singleton is Class but the dimension of pattern of flyweight is different  key of hash(you can assign key whatever you want)

 How is the pattern of flyweight applied into source of code

in String we use it

s1==s2((in fact when the code compiled the 'hello' has been assign into pool of constant,as a result s1 and s2 are assign a same address of constant ,so that they are equal) )

s1==s3 (like s1==s2)

s1==s4 (in s4 actually there where 3 space the  first is 'hel' and second is 'new String' and 'lo' also,therefore they are not equal) so on

 sum up: in base class of String has a pool of constant if two constant are equal it will be assign the same address(like pattern of pattern)

 public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "hello";
        String s3 = "he" + "llo";
        String s4 = "hel" + new String("lo");
        String s5 = new String("hello");
        String s6 = s5.intern();
        String s7 = "h";
        String s8 = "ello";
        String s9 = s7 + s8;
        System.out.println(s1==s2);//true
        System.out.println(s1==s3);//true
        System.out.println(s1==s4);//false
        System.out.println(s1==s9);//false
        System.out.println(s4==s5);//false
        System.out.println(s1==s6);//true
    }

in interger(java.lang.Integer#valueOf(int))

       Integer a = Integer.valueOf(100);
        Integer b = 100;

        Integer c = Integer.valueOf(1000);
        Integer d = 1000;

        System.out.println("a==b:" + (a == b));
        System.out.println("c==d:" + (c == d));

 To explain:

why do we pass on 100 and 1000 result the different consequence->(the low of cache is -128 and the high of its is 127 if the number we pass on is included in the area. it will create a new instance )

 Sum up:

advantage:

It can extremely reduce number of  instances,so that the same instances are kept in memory

disadvantage:

make sysmtem more complex, as the interger you should not know key you pass on  numbers greater than 127 will create a new instances ,if you did not looking up sorce of code

原文地址:https://www.cnblogs.com/UpGx/p/14733236.html