JAVA学习19---static关键字与单例模式的使用

static关键字

static可以用来修饰:属性、方法、代码块、内部类

  • 使用static修饰属性
public  class  demo{
    public static void main(String[] args) {
        chinese a = new chinese();
        a.age=12;
        a.name="张三";
        a.nation="中国";
        chinese b = new chinese();
        b.age=12;
        b.name="李四";
        System.out.println(b.nation);//打印中国
    }
}
class chinese{
    String name;
    int age;
    static String nation;
}

静态变量随着类的加载而加载,早于对象的创建

  • 使用static修饰方法:
public  class  demo{
    public static void main(String[] args) {
        chinese.say();
    }
}
class chinese{
    String name;
    int age;
    static String nation;
    public static void say(){
        System.out.println("我是中国人");
    }
}

静态方法中,只能调用静态的方法或属性,不能使用this、super关键字
非静态方法中,既可以调用非静态的方法或属性,又可以调用静态的方法或属性

设计模式

设计模式是在大量的实践中总结和理论化之后优选的代码结构、编程风格以及解决问题的思考方式

  • 单例设计模式

某个类只存在一个实例对象,构造器的访问权限设置为private
饿汉式实现:

public class demo{
    public static void main(String[] args) {
        commander a = commander.getInstance();
        System.out.println(a.name);
    }
}
class commander{
    public String name="张三";
    //私有化类的构造器,防止外部调用
    private commander(){
    }
    //内部创建类的静态对象
    private static commander instance = new commander();
    public static commander getInstance(){
        return instance;
    }
}

懒汉式实现:

public class demo{
    public static void main(String[] args) {
        commander a = commander.getInstance();
        System.out.println(a.name);
    }
}
class commander{
    public String name="张三";
    //私有化类的构造器,防止外部调用
    private commander(){
    }
    static commander instance = null;
    public static commander getInstance(){
        if(instance==null)
            instance = new commander();
        return instance;
    }
}
  • 单例模式优点
    减少了系统性能开销
  • 单例模式的应用场景
    网站的计数器
    应用程序的日志应用
    数据库连接池
    读取配置文件的类
    Application
    Task Manager
    Recycle Bin
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值