首页 > 其他 > 详细

策略模式

时间:2015-09-21 02:02:07      阅读:222      评论:0      收藏:0      [点我收藏+]


bubuko.com,布布扣
?应用场景:某商店临时搞促销活动,普通用户打9折满10元送牙刷,老用户打8折满20送枕头,Vip用户打7折满50送mp3

public class User {
	private String name;
	private int type;//假设数据库中 0代表普通用户 ,1代表老用户,2代表Vip用户
	public User(String name, int type) {
		this.name = name;
		this.type = type;
	}

?

? ??

public interface Istrategy {
    double getPrice(double price);
    String getGift();
}

? ??

public class OldUserStrategy implements Istrategy{
	private double price;
	@Override
	public double getPrice(double price) {
		this.price=price*0.8;
		return this.price;
	}
	@Override
	public String getGift() {
		if(this.price>=20){
			return "枕头";
		}
		return null;
	}
}

?

public class Content {
	private User user;
	private Istrategy istrategy;
	public void contentInterface(double price){
		if(user.getType()==0){//普通用户
			istrategy=new UserStrategy();
		}else if (user.getType()==1) {//老用户
			istrategy=new OldUserStrategy();
		}else if (user.getType()==2) {//vip用户
			istrategy=new VipUserStrategy();
		}
		System.out.println(user.getName()+"用户来消费:"+istrategy.getPrice(price));
		String gift=istrategy.getGift();
		if(gift!=null){
		    System.out.println("得到礼物:"+istrategy.getGift());
		}else {
			System.out.println("没有礼物");
		}
	}
	public void setUser(User user) {
		this.user = user;
	}
}

?

public class MainTest {
	public static void main(String[] args) {
		 //弄3个假用户
		 User zs=new User("zs", 0);
		 User ls=new User("ls", 1);
		 User ww=new User("ww", 2);
		 //开始测试
		 Content content=new Content();
		//普通用户来消费
		 content.setUser(zs);
		 content.contentInterface(18);		 
		//老用户来消费 
		 content.setUser(ls);
		 content.contentInterface(28);
		//Vip用户来消费
		 content.setUser(ww);
		 content.contentInterface(50);
	}
}

?

策略模式

原文:http://h496950806.iteye.com/blog/2244903

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!