Android的开发之&java23中设计模式------享元模式

享元模式

它使用共享物件,用来尽可能减少内存使用量以及分享资讯给尽可能多的相似物件;
它适合用于只是因重复而导致使用无法令人接受的大量内存的大量物件。通常物件中的部分状态是可以分享。

 
 
public class FlyweightMethodActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flyweight_method);
        String exercise="篮球";
        for (int i=0;i<5; i++){
            Gymnasium gymnasium=ArchitectureFactory.getGymnasium(exercise);
            gymnasium.setName("北京体育馆");
            gymnasium.setShape("圆形");
            gymnasium.use();
            System.out.print("对象池中对象数量为:"+ArchitectureFactory.getSize());
        }
    }
}
/**
 * Created by Administrator on 2017-10-9.
 * 体育馆
 */
public class Gymnasium implements Architecture {
    private String name;
    private String shape;
    private String exercise;
    public Gymnasium(String exercise){
        this.setExercise(exercise);
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getShape() {
        return shape;
    }
    public void setShape(String shape) {
        this.shape = shape;
    }
    public String getExercise() {
        return exercise;
    }
    public void setExercise(String exercise) {
        this.exercise = exercise;
    }
    @Override
    public void use() {
        System.out.print("名称为:"+name+"   运动为:"+exercise+"    形状为:"+shape);
    }
}
public class ArchitectureFactory {
    private static final Map<String,Gymnasium> gymnasium=new HashMap<>();
    public static Gymnasium getGymnasium(String exercise){
        Gymnasium gy=gymnasium.get(exercise);
        if (gy == null){
            gy = new Gymnasium(exercise);
            gymnasium.put(exercise,gy);
        }
        return gy;
    }
    public static int getSize(){
        return gymnasium.size();
    }
}
/**
 * Created by Administrator on 2017-10-9.
 * 建筑接口
 */
public interface Architecture {
    void use();
}

使用场景
     如果一个应用程序使用了大量的对象,而这些对象造成了很大的存储开销的时候就可以考虑是否可以使用享元模式。
     例如,如果发现某个对象的生成了大量细粒度的实例,并且这些实例除了几个参数外基本是相同的,如果把那些共享参数移到类外面,在方法调用时将他们传递进来,就可以通过共享大幅度单个实例的数目。

github地址:https://github.com/zyj18410105150/DesignMode


猜你喜欢

转载自blog.csdn.net/jie1123161402/article/details/80383382
今日推荐