android javabeans 和 单例

2019-07-24  本文已影响0人  DouMarK

javabeans

当我们需要对程序设置一些属性和数据的时候,可以创建一个javabeans,然后提供一些setxx/getxx方法这样就可以获取和设置这些属性了。例如使用jackson解析等,javabean属于MVC模式中的数据层。

public class Diary{

    //Create Diary constant
    private String theme;
    
    private String content;
    
    private String time;
    
    public String getContent() {
        return content;
    }
    
    public String getTheme() {
        return theme;
    }
    
    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }
    
    public void setTheme(String theme) {
        theme = theme;
    }

    public void setContent(String content) {
        content = content;
    }
}

这样在其他类调用的时候,直接实例化,然后setxx/getxx就可以设置/获取这些属性了


单例:

饿汉模式:

1、单例类只能有一个实例。
2、单例类必须自己创建自己的唯一实例。
3、单例类必须给所有其他对象提供这一实例。

模式的使用场景

确保某个类有且只有一个对象的场景,例如创建一个对象需要消耗的资源过多,如要访问 IO 和数据库等资源。

代码实现:

如以下日记常量代码
在声明时自动初始化

public class Diary{
    
    private static final diary theme = new diary();

    private static final diary content = new diary();

    private static final diary time = new diary();

    private Diary(){
        
    }
    
    public static diary getTheme() {
        return theme;
    }

    public static diary getContent() {
        return content;
    }

    public static diary getTime() {
        return time;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读