策略模式处理不同邮箱异常
2022-02-20 本文已影响0人
lenny611
顶层策略接口
package strategy;
public interface MailExceptionStrategy {
void handleException();
}
qq邮箱异常处理策略
package strategy;
public class QQExceptionStrategy implements MailExceptionStrategy{
public void handleException() {
System.out.println("this is QQMailException!");
}
}
outlook邮箱处理策略
package strategy;
public class OutlookExceptionStrategy implements MailExceptionStrategy{
public void handleException() {
System.out.println("this is outlookMailException!");
}
}
新增的网易邮箱异常处理策略
package strategy;
public class NeteaseExceptionStrategy implements MailExceptionStrategy{
@Override
public void handleException() {
System.out.println("this is 163Exception");
}
}
策略上下文
package strategy;
public class MailExceptionStrategyContext {
private MailExceptionStrategy strategy;
public void handle(MailExceptionStrategy strategy){
this.strategy=strategy;
strategy.handleException();
}
public void handle(String emailAddress){
final String mailType = MailType.getTypeByEmailAddress(emailAddress);
final MailExceptionStrategy strategy = getStrategyByMailType(mailType);
handle(strategy);
}
private MailExceptionStrategy getStrategyByMailType(String mailType){
if (MailType.QQ.getEmailType().equals(mailType)){
return new QQExceptionStrategy();
}else if (MailType.OUTLOOK.getEmailType().equals(mailType)){
return new OutlookExceptionStrategy();
}else if (MailType.NETEASE.getEmailType().equals(mailType)){
return new NeteaseExceptionStrategy();
} else {
return new DefaultExceptionStrategy();
}
}
}
邮箱类型枚举类
package strategy;
public enum MailType {
QQ("qq邮箱","qq"),
OUTLOOK("outlook邮箱","outlook"),
NETEASE("网易邮箱","163"),
UNKNOWN("未知邮箱","unknown")
;
private String name;
private String emailType;
MailType(String name, String emailType) {
this.name = name;
this.emailType = emailType;
}
public String getName() {
return name;
}
public String getEmailType() {
return emailType;
}
public static String getTypeByEmailAddress(String emailAddress){
for (MailType mailType : MailType.values()) {
if (emailAddress.contains(mailType.getEmailType())){
System.out.println("this email type is "+mailType.getEmailType());
return mailType.getEmailType();
}
}
System.out.println("this email type is "+MailType.UNKNOWN.getEmailType());
return MailType.UNKNOWN.getEmailType();
}
}
运行主类
package strategy;
public class MailRun {
public static void main(String[] args) {
String qqMail="123456789@qq.com";
String outlookMail="123456789@outlook.com";
String unknownMail="123111@163.com";
MailExceptionStrategyContext context=new MailExceptionStrategyContext();
context.handle(unknownMail);
}
}