JAVA基础10--行为型模式(责任链模式 迭代器模式 中介者模式 命令模式 策略模式)

案例 责任链模式

将能够处理同一类请求的对象连成一条链,所提交的请求沿着链传递,链上的对象逐个判断是否有能力处理该请求,如果能则处理,如果不能则传递给连上的下一个对象
public class Client {
	public static void main(String[] args) {
		Leader a = new Director("张三");
		Leader b = new Manager("李四");
		Leader c = new GeneralManager("王五");
		//组织责任链对象的关系
		a.setNextLeader(b);
		b.setNextLeader(b2);
		b2.setNextLeader(c);
		//开始请假操作
		LeaveRequest req1 = new LeaveRequest("TOM", 15, "回英国老家探亲!");
		a.handleRequest(req1);
	}
}
public abstract class Leader {
	protected String name;
	protected Leader nextLeader; //责任链上的后继对象
	public Leader(String name) {
		super();
		this.name = name;
	}
	//设定责任链上的后继对象
	public void setNextLeader(Leader nextLeader) {
		this.nextLeader = nextLeader;
	}
	/**
	 * 处理请求的核心的业务方法
	 * @param request
	 */
	public abstract void handleRequest(LeaveRequest request);
}
public class Director extends Leader {
	public Director(String name) {
		super(name);
	}
	@Override
	public void handleRequest(LeaveRequest request) {
		if(request.getLeaveDays()<3){
			System.out.println("员工:"+request.getEmpName()+"请假,天数:"+request.getLeaveDays()+",理由:"+request.getReason());
			System.out.println("主任:"+this.name+",审批通过!");
		}else{
			if(this.nextLeader!=null){
				this.nextLeader.handleRequest(request);
			}
		}
	}
}
public class Manager extends Leader {
	public Manager(String name) {
		super(name);
	}
	@Override
	public void handleRequest(LeaveRequest request) {
		if(request.getLeaveDays()<10){
			System.out.println("员工:"+request.getEmpName()+"请假,天数:"+request.getLeaveDays()+",理由:"+request.getReason());
			System.out.println("经理:"+this.name+",审批通过!");
		}else{
			if(this.nextLeader!=null){
				this.nextLeader.handleRequest(request);
			}
		}
	}
}
public class GeneralManager extends Leader {

	public GeneralManager(String name) {
		super(name);
	}
	@Override
	public void handleRequest(LeaveRequest request) {
		if(request.getLeaveDays()<30){
			System.out.println("员工:"+request.getEmpName()+"请假,天数:"+request.getLeaveDays()+",理由:"+request.getReason());
			System.out.println("总经理:"+this.name+",审批通过!");
		}else{
			System.out.println("莫非"+request.getEmpName()+"想辞职,居然请假"+request.getLeaveDays()+"天!");
		}
	}
}


案例  迭代器

提供一种可以遍历聚合对象的方式,又称为 :游标cursor模式
聚合对象:存储数据
迭代器:遍历数据
public class Client {
	public static void main(String[] args) {
		ConcreteMyAggregate cma = new ConcreteMyAggregate();
		cma.addObject("aa");
		cma.addObject("bb");
		cma.addObject("cc");
		MyIterator iter = cma.createIterator();
		while(iter.hasNext()){
			System.out.println(iter.getCurrentObj());
			iter.next();
		}
	}
}

public interface MyIterator {
	void first();	//将游标指向第一个元素
	void next();	//将游标指向下一个元素
	boolean hasNext();//判断是否存在下一个元素
	boolean isFirst();
	boolean isLast();
	Object getCurrentObj();  //获取当前游标指向的对象
}
/**
 * 自定义的聚合类
 * @author Administrator
 *
 */
public class ConcreteMyAggregate {
	private List<Object> list = new ArrayList<Object>();
	public void addObject(Object obj){
		this.list.add(obj);
	}
	public void removeObject(Object obj){
		this.list.remove(obj);
	}
	public List<Object> getList() {
		return list;
	}
	public void setList(List<Object> list) {
		this.list = list;
	}
	//获得迭代器
	public MyIterator  createIterator(){
		return new ConcreteIterator();
	}
	//使用内部类定义迭代器,可以直接使用外部类的属性
	private class ConcreteIterator implements MyIterator {
		private int cursor;  //定义游标用于记录遍历时的位置
		@Override
		public void first() {
			cursor = 0;
		}
		@Override
		public Object getCurrentObj() {
			return list.get(cursor);
		}
		@Override
		public boolean hasNext() {
			if(cursor<list.size()){
				return true;
			}
			return false;
		}
		@Override
		public boolean isFirst() {
			return cursor==0?true:false;
		}
		@Override
		public boolean isLast() {
			return cursor==(list.size()-1)?true:false;
		}
		@Override
		public void next() {
			if(cursor<list.size()){
				cursor++;
			}
		}
	}	
}


案例 中介者模式

public interface Mediator {
	void register(String dname,Department d);
	void command(String dname);
}
//同事类的接口
public interface Department {
	void selfAction(); //做本部门的事情
	void outAction();  //向总经理发出申请
}
public class Development implements Department {
	private Mediator m;  //持有中介者(总经理)的引用
	public Development(Mediator m) {
		super();
		this.m = m;
		m.register("development", this);
	}
	@Override
	public void outAction() {
		System.out.println("汇报工作!没钱了,需要资金支持!");
	}
	@Override
	public void selfAction() {
		System.out.println("专心科研,开发项目!");
	}
}
public class Finacial implements Department {

	private Mediator m;  //持有中介者(总经理)的引用
	
	public Finacial(Mediator m) {
		super();
		this.m = m;
		m.register("finacial", this);
	}
	@Override
	public void outAction() {
		System.out.println("汇报工作!没钱了,钱太多了!怎么花?");
	}
	@Override
	public void selfAction() {
		System.out.println("数钱!");
	}
}
public class Market implements Department {
	private Mediator m;  //持有中介者(总经理)的引用
	public Market(Mediator m) {
		super();
		this.m = m;
		m.register("market", this);
	}
	@Override
	public void outAction() {
		System.out.println("汇报工作!项目承接的进度,需要资金支持!");
		m.command("finacial");	
	}
	@Override
	public void selfAction() {
		System.out.println("跑去接项目!");
	}
}
public class President implements Mediator {
	private Map<String,Department> map = new HashMap<String , Department>();
	@Override
	public void command(String dname) {
		map.get(dname).selfAction();
	}
	@Override
	public void register(String dname, Department d) {
		map.put(dname, d);
	}
}

public class Client {
	public static void main(String[] args) {
		Mediator m = new President();
		Market   market = new Market(m);
		Development devp = new Development(m);
		Finacial f = new Finacial(m);
		market.selfAction();
		market.outAction();
	}
}


案例  命令模式

命令模式:将一个请求封装为一个对象,从而使我们可用不同的请求对客户进行参数化;对请求排队或者记录请求日志,以及支持可撤销的操作,也称之为:动作action模式,事物transaction模式
/**
 * 真正的命令的执行者
 * @author Administrator
 *
 */
public class Receiver {
	public void action(){
		System.out.println("Receiver.action()");
	}
}
public interface Command {
	/**
	 * 这个方法是一个返回结果为空的方法。
	 * 实际项目中,可以根据需求设计多个不同的方法
	 */
	void execute();
}

class ConcreteCommand implements Command {
	private Receiver receiver;	//命令的真正的执行者
	public ConcreteCommand(Receiver receiver) {
		super();
		this.receiver = receiver;
	}
	@Override
	public void execute() {
		//命令真正执行前或后,执行相关的处理!
		receiver.action();
	}
}
public class Invoke {
	private Command command;   //也可以通过容器List<Command>容纳很多命令对象,进行批处理。数据库底层的事务管理就是类似的结构!
	public Invoke(Command command) {
		super();
		this.command = command;
	} 
	//业务方法 ,用于调用命令类的方法
	public void call(){
		command.execute();
	}
}


案例 策略模式

策略模式对应于解决某一个问题的一个算法族,允许用户从该算法族中任选一个算法解决某一问题,同时可以方便的更换算法或者增加新的算法。并且由客户端决定调用哪个算法
public class Client {
	public static void main(String[] args) {
		Strategy s1 = new NewCustomerFewStrategy();
		Context ctx = new Context(s1);	
		ctx.pringPrice(998);
	}
}
public class Context {
	private Strategy strategy;	//当前采用的算法对象
	//可以通过构造器来注入
	public Context(Strategy strategy) {
		super();
		this.strategy = strategy;
	}
	//可以通过set方法来注入
	public void setStrategy(Strategy strategy) {
		this.strategy = strategy;
	}
	public void pringPrice(double s){
		System.out.println("您该报价:"+strategy.getPrice(s));
	}
}
public interface Strategy {
	public double getPrice(double  standardPrice);
}
public class NewCustomerFewStrategy implements Strategy {
	@Override
	public double getPrice(double standardPrice) {
		System.out.println("不打折,原价");
		return standardPrice;
	}
}
public class NewCustomerManyStrategy implements Strategy {
	@Override
	public double getPrice(double standardPrice) {
		System.out.println("打九折");
		return standardPrice*0.9;
	}
}



案例 模板方法模式 

public abstract class BankTemplateMethod {
	//具体方法
	public void takeNumber(){
		System.out.println("取号排队");
	}
	public abstract void transact(); //办理具体的业务	//钩子方法
	public void evaluate(){
		System.out.println("反馈评分");
	}
	public final void process(){	//模板方法!!!
		this.takeNumber();

		this.transact();

		this.evaluate();
	}
}

public class Client {
	public static void main(String[] args) {
		BankTemplateMethod btm = new DrawMoney();
		btm.process();
		//采用匿名内部类
		BankTemplateMethod btm2 = new BankTemplateMethod() {
			@Override
			public void transact() {
				System.out.println("我要存钱!");
			}
		};
		btm2.process();
		BankTemplateMethod btm3 = new BankTemplateMethod() {
			@Override
			public void transact() {
				System.out.println("我要理财!我这里有2000万韩币");
			}
		};
		btm3.process();
	}
}

class DrawMoney extends BankTemplateMethod {
	@Override
	public void transact() {
		System.out.println("我要取款!!!");
	}
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值