第三章④设计模式

2019-05-04  本文已影响0人  犀首_0c79

设计模式:

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

共有23种设计模式。

单例设计模式:使得一个类只能创建一个对象

如何实现:

1.私有化构造器,使得外部不能调用此构造器

2.在此类内部创建一个类的对象

3.私有化此对象通过公共的方法来调用

4.此公共的方法只能通过类来调用,因为设置为static的,所以就成为类变量

public class TestSingLeton {

public static void main(String[]args) {

SingLeton s1 =SingLeton.getInstance();

        SingLeton s2 =SingLeton.getInstance();

        System.out.println(s1==s2);

    }

}

//只能创建SingLeton的单个对象(实例)

class SingLeton {

//1.私有化构造器,使得外部不能调用此构造器

    private SingLeton() {

}

//2.在此类内部创建一个类的对象

    private static SingLeton instance =new SingLeton();

//3.私有化此对象通过公共的方法来调用

//4.此公共的方法只能通过类来调用,因为设置为static的,所以就成为类变量

    public static SingLeton getInstance() {

return instance;

    }

}


上一篇 下一篇

猜你喜欢

热点阅读