package com.enumMe;
import java.util.Random;
class Mail
{
/*
* 定义自定义类型
*/
enum Adress
{
error, ok1, ok2, ok3
};
enum PostCode
{
none, ok, good
};
enum Sender
{
bad, nice, yes
}
public <T extends Enum<T>> T random(Class<T> t)
{
Random random = new Random();
T[] enumConstants = t.getEnumConstants();
return enumConstants[random.nextInt(enumConstants.length)];
}
/*
* 定义成员变量
*/
private Adress adress = random(Adress.class);
private PostCode postCode = random(PostCode.class);
private Sender sender = random(Sender.class);
public Adress getAdress()
{
return adress;
}
public void setAdress(Adress adress)
{
this.adress = adress;
}
public PostCode getPostCode()
{
return postCode;
}
public void setPostCode(PostCode postCode)
{
this.postCode = postCode;
}
public Sender getSender()
{
return sender;
}
public void setSender(Sender sender)
{
this.sender = sender;
}
@Override
public String toString()
{
return "Mail [adress=" + adress + ", postCode=" + postCode + ", sender=" + sender + "]";
}
}
public class Poster
{
enum MailHandler
{
Check_Adress
{
@Override
boolean handle(Mail m)
{
switch (m.getAdress())
{
case error:
System.out.println("Adress is error !");
return false;
default:
System.out.println("Adress is ok !");
return true;
}
}
},
Check_postCode
{
@Override
boolean handle(Mail m)
{
switch (m.getPostCode())
{
case none:
System.out.println("PostCode is error !");
return false;
default:
System.out.println("PostCode is ok !");
return true;
}
}
},
Check_Sender
{
@Override
boolean handle(Mail m)
{
switch (m.getSender())
{
case bad:
System.out.println("Sender is error !");
return false;
default:
System.out.println("Sender is ok !");
return true;
}
}
};
abstract boolean handle(Mail m);
}
public void handle(Mail m)
{
for (MailHandler hd : MailHandler.values())
if (!hd.handle(m))
{
System.out.println(m + " is a dead letter.");
return;
}
System.out.println(m + " is a fine letter.");
}
public static void main(String[] args)
{
Poster post = new Poster();
Mail m1 = new Mail();
System.out.println(m1);
post.handle(m1);
System.out.println("***********************");
Mail m2 = new Mail();
System.out.println(m2);
post.handle(m2);
System.out.println("***********************");
Mail m3 = new Mail();
System.out.println(m3);
post.handle(m3);
System.out.println("***********************");
}
}
枚举实现的责任链_demo_me
最新推荐文章于 2024-04-19 10:29:26 发布