设计模式-享元模式

设计模式-享元模式

定义

又称为轻量级模式,是对象池的一种实现。类似于线程池,线程池可以避免不停地创建和销毁多个对象,消耗性能。提供了减少对象数量从而改善应用所需的对象结构的方式。

宗旨:共享细粒度对象,将多个对同一对象的访问集中起来。

属于结构型。

应用场景

  • 常常用于系统底层的开发,以便解决系统的性能问题
  • 系统有大量相似的对象、需要缓冲池的场景

代码示例

创建 ITicket 接口

package com.black.design.pattern.flyweight.ticket;

//票
public interface ITicket {

//    显示票面信息
    void showInfo(String bunk);
}

创建一个 ITicket 接口实现类-火车票

package com.black.design.pattern.flyweight.ticket;

import java.math.BigDecimal;
import java.util.Random;

import javax.swing.tree.VariableHeightLayoutCache;

//火车票
public class TrainTicket implements ITicket {

    //起点
    private String from;
    //终点
    private String to;
    //价格
    private Double price;

    public TrainTicket(String from, String to) {
        this.from = from;
        this.to = to;
    }

    public void showInfo(String bunk) {
        Integer i =(Integer) new Random().nextInt(999);
        BigDecimal bi = new BigDecimal(i.toString());
        Double d = new Random().nextDouble();
        BigDecimal bd = new BigDecimal(d.toString());
        this.price = bi.add(bd).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        System.out.println("【"+from + "】到【" + to  +"】【" + bunk + "】价格:" + price);
    }

}

创建一个 享元工厂 用于

package com.black.design.pattern.flyweight.ticket;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

// 工厂
public class TicketFactory {

    //pool 缓存票据信息
    private static Map<String, ITicket> pool = new ConcurrentHashMap<String, ITicket>();

    public static ITicket getTicket(String from, String to) {
        String keyString = from+"->" + to;
        if(!pool.containsKey(keyString)) {
            ITicket ticket = new TrainTicket(from, to);
            pool.put(keyString, ticket);
        }
        return pool.get(keyString);  
    }
}

创建测试类

package com.black.design.pattern.flyweight.ticket;
//测试类
public class TicketTest {

    public static void main(String[] args) {
        TicketFactory ticketFactory = new TicketFactory();
        ITicket t1 =  ticketFactory.getTicket("郑州", "北京");
        t1.showInfo("硬座");
        ITicket t2 =  ticketFactory.getTicket("郑州", "焦作");
        t2.showInfo("软卧");
    }
    
}

设计模式-享元模式

上一篇:题解 AT3534 [ARC083A] Sugar Water


下一篇:11-pyecharts使用Tab不完全代码示例