?应用场景:某商店临时搞促销活动,普通用户打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