Strategy策略模式Java示例学习

找出应用中的可能变化之处,将他们独立出来,将其他不变化的部分放在一起

多用组合,少用继承

面向接口编程,而不是面向实现编程

 

假设要出门旅行,考虑创建一系列交通工具来供调用

 

首先考虑不同处:

public interface IFlyBehavior
{
	void fly();
}


 

public interface IPriceBehavior
{
	void price();
}


然后是这几种不同分别有几种情况:

public class CanFly implements IFlyBehavior
{
	@Override
	public void fly()
	{
		System.out.println("i can fly");
	}
}


 

public class CannotFly implements IFlyBehavior
{
	@Override
	public void fly()
	{
		System.out.println("i can't fly");
	}
}


 

 

public class HighPrice implements IPriceBehavior
{
	@Override
	public void price()
	{
		System.out.println("my price high");
	}
}


 

public class MedPrice implements IPriceBehavior
{
	@Override
	public void price()
	{
		System.out.println("my price mediate");
	}
}


 

public class LowPrice implements IPriceBehavior
{
	@Override
	public void price()
	{
		System.out.println("my price low");
	}
}


交通工具的模板,包含其共同之处

public abstract class Vehicle
{
	protected IFlyBehavior fly;
	protected IPriceBehavior price;

	public void performFly()
	{
		fly.fly();
	}

	public void perPrice()
	{
		price.price();
	}

	public void run()
	{
		System.out.println("i can run");
	}

	public abstract void select();

}


 

那么,就可以分别创建汽车,火车和飞机等:

public class Bus extends Vehicle
{
	public Bus()
	{
		fly = new CannotFly();
		price = new MedPrice();
	}

	@Override
	public void select()
	{
		fly.fly();
		price.price();
	}
}


 

public class Train extends Vehicle
{

	public Train()
	{
		fly = new CannotFly();
		price = new LowPrice();
	}

	@Override
	public void select()
	{
		fly.fly();
		price.price();
	}
	
}


 

public class Plane extends Vehicle
{

	public Plane()
	{
		fly = new CanFly();
		price = new HighPrice();
	}

	@Override
	public void select()
	{
		fly.fly();
		price.price();
	}

}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值