单例设计模式

来源:互联网 发布:mac美国官网价格 编辑:程序博客网 时间:2024/06/13 00:03
 * 单例设计模式:解决一个类在内存只存在一个对象。  * 想要保证对象唯一 * 1、为了避免其他程序过多建立该类对象。先控制进制其他程序建立该类对象 * 2、还为了让其他程序可以访问到该对象,只好在本类中,自定义一个对象。 * 3、为了方便其他程序对自定义对象的访问,可以对外提供一些访问方式。 * 这三步怎么用代码体现呢? * 1、将构造函数私有化 * 2、在类中创建一个本类对象。 * 3、提供一个方法可以获取到该对象 * 对于事物该怎么描述,还怎么描述 * 当需要将该事物的对象保证在内存中唯一时,就将以上的三步加上即可。 */package com.hao947.SingleDemo;class Single{private int num;public  void setNum(int num){this.num = num;}public int getNum(){return num;}//单例private Single(){}private static SingleThread s = new SingleThread();public static SingleThread getInstance(){return s;}}public class SingleDemo {public static void main(String[] args){/*Single s1 = new Single();Single s2 = new Single();s1.setNum(30);System.out.println(s2.getNum());*/SingleThread s1 = SingleThread.getInstance();SingleThread s2 = SingleThread.getInstance();s1.setNum(23);System.out.println(s2.getNum());Student s11 = Student.getStudent();Student s12 = Student.getStudent();}}//用单例class Student{private int age;private static Student s = new Student();private Student(){}public static Student getStudent(){return s;}public void setAge(int age){this.age = age;}public int getAge(){return age;}}class Car{//颜色String color = "红色";//轮胎数量int num = 4;//运行行为void run(){System.out.println(color+"..."+num);}}class CarDemo{public static void main(String[] args){//在计算机中创建一个car的实例。通过new关键字。Car c = new Car();// c就是一个类类型变量 记住:类类型变量指向对象。c.color = "red";c.num = 4;c.run(); //要使用对象中得内容可以通过  对象.成员   的形式来完成调用。Car c1 = new Car();c1.num = 4;c1.color = "red";Car c2 = new Car();c2.num = 4;c2.color = "red";new Car().num = 4; //匿名对象调用。//匿名对象使用方式一:当对象的方法只调用一次时,可以用匿名对象来完成,这样写比较简化。//如果对象一个对象进行多个成员调用,必须给这个对象起个名字。//匿名对象使用方式二:可以将匿名对象作为实际参数进行传递。Car q = new Car();show(q);}//需求:汽车修配厂,对汽车进行改装,将来得车修改成黑车,三个轮胎。public static void show (Car c){c.num = 3;c.color = "black";c.run();}}

原创粉丝点击