java设计模式-享元模式

什么是享元模式:
为了节省内存,共享一个对象,提供内存使用率,享元模式的关键在于区分共享的内部状态和非共享的外部状态。

开发中常见的享元模式场景:
1.JDBC连接池,线程池
2.java String类的设计

享元模式例子:
实现的场景是游戏中的飞机打出的子弹,子弹有级别和位置,级别状态可以共享,而位置状态不能共享。

/**
 * 子弹类
 * @author liuxg
 * @date 2016年5月27日 下午5:41:46
 */
public class Bullet {

    private String level ; //可以共享的状态

    public Bullet(String level) {
        super();
        this.level = level;
    }


    /**
     * 发射子弹
     */
    public void send(Postion position){ //position不可以共享

        System.out.println(level + "发送 ->位置 :" + position.getX() + "," + position.getY());

    }


}

position类状态不可以共享,因为位置时时不一样,position类如下

/**
 * 子弹位置
 * @author liuxg
 * @date 2016年5月27日 下午5:47:55
 */
public class Postion {

    private int x ;
    private int y;

    public Postion(int x, int y) {
        super();
        this.x = x;
        this.y = y;
    }
    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public int getY() {
        return y;
    }
    public void setY(int y) {
        this.y = y;
    } 


}

我们这里还是用了工厂模式,用来管理和创建子弹

/**
 * 子弹工厂类,用来创建子弹
 * @author liuxg
 * @date 2016年5月27日 下午5:42:09
 */
public class BulletFactory {

    private static Map<String, Bullet> map = new HashMap<String,Bullet>();//用于存放子弹

    /**
     * 发射子弹
     */
    public static Bullet getBullet(String level){
        Bullet b = null ;
        if (map.get(level) == null) {
            b = new Bullet("导弹");
            map.put(level, b);
        }else{
            b = map.get(level);
        }

        return b ; 
    }

}

客户端我们就可以这么调用了

public class Client {

    public static void main(String[] args) {

        Bullet b1 = BulletFactory.getBullet("导弹");
        b1.send(new Postion(12, 32));

        Bullet b2 = BulletFactory.getBullet("导弹");
        b2.send(new Postion(22, 22));

        System.out.println(b1 == b2);//b1和b2为指向同一个地址


    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值