代理模式实例订单系统
一旦订单被创建,只有订单的创建人才可以修改订单中的数
据,其他人则不能修改。
三个属性:产品名称、订购数量、订购人
成员接口
package daili;
public interface OrderApi {
public String getProductName();
public void setProductName(String productName, String user);
public int getOrderNum();
public void setOrderNum(int orderNum,String user);
public String getOrderUser();
public void setOrderUser(String orderUser, String user);
}
Order
package daili;
public class Order implements OrderApi {
private String productName;
private int orderNum;
private String orderUser;
public Order(String productName, int orderNum, String orderUser) {
this.productName = productName;
this.orderNum = orderNum;
this.orderUser = orderUser;
}
public Order() {}
@Override
public String getProductName() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setProductName(String productName, String user) {
// TODO Auto-generated method stub
}
@Override
public int getOrderNum() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void setOrderNum(int orderNum, String user) {
// TODO Auto-generated method stub
}
@Override
public String getOrderUser() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setOrderUser(String orderUser, String user) {
// TODO Auto-generated method stub
}
}
OrderProxy
package daili;
public class OrderProxy implements OrderApi {
private Order order=null;
public OrderProxy(Order order) {
this.order = order;
}
@Override
public String getProductName() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setProductName(String productName, String user) {
if(user!=null && user.equals(this.getOrderUser()))
{order.setProductName(productName, user);
}else {
System.out.println("对不起"+user+", 您无权修改订单中的产品名称");
}
}
@Override
public int getOrderNum() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void setOrderNum(int orderNum, String user) {
if(user!=null && user.equals(this.getOrderUser())) {
order.setOrderNum(orderNum, user);
}else {
System.out.println("对不起" +user+",您无权修改订单中的订购数量");
}
}
@Override
public String getOrderUser() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setOrderUser(String orderUser, String user) {
if(user!=null && user.equals(this.getOrderUser())) {
order.setOrderUser(orderUser, user);
}else {
System.out.println("对不起" +user+",您无权修改订单中的订购人");
}
}
}
测试
package daili;
public class test {
public static void main(String[] args) {
OrderApi order=new OrderProxy(new Order("设计模式",100," 张三 ="));
order. setOrderNum(123, "李四");
System.out.println("李四修改后订单记录没有变化: "+order);
order.setOrderNum(123,"张三");
System.out.println("张三修改后订单记录: "+order);
}
}