现在让我们举个例子,创建两个人,因为在交易中所处的角色不同,而执行不同的行为。
首先,创建产品
public class Product
...{
private String name;
private String description;
private double cost;
public Product(String name,String description,double cost)
...{
this.name = name;
this.description = description;
this.cost = cost;
}
public double getCost()
...{
return cost;
}
public String getDescription()
...{
return description;
}
public void setDescription(String description)
...{
this.description = description;
}
public String getName()
...{
return name;
}
public void setName(String name)
...{
this.name = name;
}
public void setCost(double cost)
...{
this.cost = cost;
}
}
然后创建一个公共的角色类,他抽象了各个角色在交易中所要达成的共同目的,就是是否对交易满意
public interface Role
...{
public boolean isSatisfied(Product product , double price);
}
接着在抽象的角色上,创建买卖双方的类。
先是卖方,他要达成满意,必须有20%的利润
public class Seller implements Role
...{
public boolean isSatisfied(Product product, double price)
...{
if (price - product.getCost() > product.getCost() * 0.2)
...{
return true;
}
else
return false;
}
}
public class Buyer implements Role
...{
private double limit;
public Buyer(double limit)
...{
this.limit = limit;
}
public boolean isSatisfied(Product product, double price)
...{
if (price < limit && price < product.getCost() * 2)
...{
return true;
}
else
return false;
}
}
最后让我们来创建交易。交易中有两个人,一个是“Tim”,一个是“Allison”。第一笔交易是一套房子,成本价是40万,Tim是买方,Allison是卖方。第二笔交易是一辆成本为5万的车子,Allison变成了买方。
public class Trade
...{
public static void main(String[] args)
...{
Product house = new Product("house", "House Cost 40WangYuan", 400000);
Product car = new Product("car", "Car Cost 5WangYuan", 50000);
Person tim = new Person("Tim");
Person allison = new Person("Allison");
tim.setRole(new Buyer(500000));
allison.setRole(new Seller());
if (!allison.satisfied(house, 400000))
...{
System.out.println(house.getDescription() + " offer of 400,000 is no good for the seller");
}
if (!tim.satisfied(house, 600000))
...{
System.out.println(house.getDescription() + " offer of 600,000 is no good for the buyer");
}
if (tim.satisfied(house, 450000))
...{
System.out.println(house.getDescription() + " they both agree with 450000");
}
allison.setRole(new Buyer(70000));
if (allison.satisfied(car, 60000))
...{
System.out.println("As a buyer she can afford the " + car.getDescription());
}
}
}
158

被折叠的 条评论
为什么被折叠?



