您的位置:首页 > 其它

单例、多例设计模式、枚举

2016-10-30 18:44 204 查看
单例设计模式:

    特征是构造方法私有化,而后在类的内部提供有一个static本类对象,并且利用static方法取得此对象。

  代码如下:

 class Singleton{
private static final Singleton INSTANCE = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return INSTANCE;
}

public void print(){
System.out.println("hello world");
}
}
public class TestDemo{
public static void main(String[] args)throws Exception {
Singleton s = Singleton.getInstance();
s.print();
}


   一定要记住封装不只是private一种方式,还包含有protect权限,往往出现在一些跨包的操作上。

    如果存在有多个对象,那么就是多例设计模式(在类的内部存在有多个对象的信息)。

    代码如下:

         class Color{
private static final Color RED = new Color("红色");
private static final Color GREEN = new Color("绿色");
private static final Color BLUE = new Color("蓝色");
private String title;
private Color(String title){
this.title=title;

}
public static Color getInstance(int ch){
switch(ch){
case 0:
return RED;
case 1:
return GREEN;
case 2:
return BLUE;
default:
return null;
}
}
public String toString(){
return this.title;

}

}

public class TestDemo{
public static void main(String[] args)throws Exception {
System.out.println(Color.getInstance(0));
System.out.println(Color.getInstance(1));
System.out.println(Color.getInstance(2));
System.out.println(Color.getInstance(3));
}

}

  在单例设计模式里面只有一个对象,所以当调用了getInstance 方法的时候可以很方便的找到制定的对象,但是如果是多例设计模式需要记住编号,太麻烦了,为此才会在jdk1.5后提供了枚举类型。

   枚举代码如下:

           enum Color{
RED("红色"),GREEN("绿色"),BLUE("蓝色");
private String title;

private Color(String title){
this.title= title;
}
public String toString(){
return this.title;

}

}

public class TestDemo{
public static void main(String[] args)throws Exception {
System.out.println(Color.RED);
System.out.println(Color.GREEN);
System.out.println(Color.BLUE);

}

}

   面试题:enum和Enum有什么的区别?哪个类使用了单例设计模式?

             -enum是一个关键字而Enum是一个类;

      -使用enum定义的枚举相当于一个类继承了Enum类;
    -Runtime类使用了单例设计模式;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: