package com.msc.design;
//多例设计模式
class Color{
private static final Color RED = new Color("红色") ;
private static final Color GREEN = new Color("绿色") ;
private static final Color BLUE = new Color("蓝色") ;
public String color ;
private Color(String color){
this.color = color ;
}
public static Color getColor(String color){
switch (color){
case "red" : return RED ;
case "green" : return GREEN ;
case "blue" : return BLUE ;
default: return null ;
}
}
public String toString(){
return this.color ;
}
}
//枚举 多例设计模式
interface IMessage{
public void print() ;
}
enum ColorB implements IMessage{
RED("红色"){
@Override
public String getMessage() {
return this.toString();
}
} , BLUE("蓝色"){
@Override
public String getMessage() {
return this.toString();
}
} , GREEN("绿色"){
@Override
public String getMessage() {
return this.toString();
}
};
private String color ;
private ColorB() {} ;
private ColorB(String color){
this.color = color ;
}
@Override
public String toString() {
return "ColorB{" +
"color='" + color + '\'' +
'}';
}
public void print(){
System.out.println("枚举实现接口");
}
public abstract String getMessage() ;
}
enum Sex{
MALE("男"),FEMALE("女") ;
private String sex ;
private Sex () {} ;
private Sex (String sex){
this.sex = sex ;
}
@Override
public String toString() {
return this.sex ;
}
}
class PersonD{
private String name ;
private Sex sex ;
public PersonD () {} ;
public PersonD (String name,Sex sex) {
this.name = name ;
this.sex = sex ;
} ;
@Override
public String toString() {
return "PersonD{" +
"name='" + name + '\'' +
", sex=" + sex +
'}';
}
}
public class Mult {
public static void main(String[] args) {
System.out.println("----------多例-------------");
Color red = Color.getColor("red");
System.out.println(red.toString());
Color blue = Color.getColor("blue");
System.out.println(blue.toString());
System.out.println("----------枚举-------------");
IMessage msg = ColorB.RED ;
msg.print();
for(ColorB c : ColorB.values()){
System.out.println(c.toString());
}
System.out.println("---------------------------");
ColorB c = ColorB.GREEN ;
System.out.println(ColorB.RED.getMessage());
System.out.println(c.getMessage());
System.out.println("----------枚举switch-------------");
switch (c){
case RED -> System.out.println(ColorB.RED.getMessage()) ;
case GREEN -> System.out.println(ColorB.GREEN.getMessage()) ;
case BLUE -> System.out.println(ColorB.BLUE.getMessage()) ;
default -> System.out.println("默认") ;
}
System.out.println("----------枚举option-------------");
System.out.println(new PersonD("张三",Sex.MALE));
}
}
剑指offer-多例设计模式
最新推荐文章于 2021-09-18 16:21:16 发布