11.15学习笔记(包)

protected类
类名称 单词首字母大写 public class TestDemo
方法名 首单词小写其他单词首字母大写 public void getInfo()
属性名 与方法名规则相同 String studentName
包名 全部小写 package cn.demo;
常量 全部大写 public static final String INFO;

单例设计模式
class Singleton{
//实例化类对象,在类里完成实例化,使用final只能定义一次
private static final Singleton instance=new Singleton();
//封装了所以需要一个静态方法返回
public static Singleton getInstace(){
return instance;
}
//构造方法私有化
private Singleton(){}
public void print(){
System.out.println(“helloworld”);
}
}
public class TestDemo{
public static void main(String args[]){
Singleton inst=null; //声明对象
// inst=new Singleton(); //实例化对象,会报错
inst=Singleton.instance;
inst.print();
}
}
多例设计模式
class Sex{
private static final Sex MALE=new Sex(“男”);
private static final Sex FEMALE=new Sex(“女”);
private String title;
private Sex(String title){
this.title=title;}
public String getTitle(){
return this.title;}
public static Sex getSex(int ch){
switch(ch)
case 0:return MALE;
case 1:return FEMALE;
default:return null;
}
}
public class TestDemo{
public static void main(String args[]){
Sex mySex=Sex.getSex(0);
System.out.println(mySex.getTitle());
}
}

猜你喜欢

转载自blog.csdn.net/weixin_43621813/article/details/84106588