- content {:toc}
设计模式和设计原则
https://www.cnblogs.com/tongkey/p/7170826.html
装饰者模式
利用继承和组合的方式实现给一个类添加不同功能 例子: 需求:手机为父类(超类),子类有小米、华为,给他们装饰内存卡、充电宝等小类 手机父类:
public abstract class Phone {
public String description = "";
public String getDescription() {
return description;
}
public abstract double cost();
}
小米:(被装饰)
public class XiaoMi extends Phone {
public XiaoMi() {
description = "小米手机";
}
@Override
public double cost() {
// TODO Auto-generated method stub
return 2000;
}
}
抽象装饰者:
public abstract class Attachment extends Phone {
//组合方式
Phone phn;
public Attachment(Phone ph) {
this.phn = ph;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return phn.getDescription();
}
@Override
public double cost() {
return phn.cost();
}
}
电池:(装饰出来的成品)
public class Battery extends Attachment {
public Battery(Phone ph) {
super(ph);
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return super.getDescription() + "电池";
}
@Override
public double cost() {
// TODO Auto-generated method stub
return super.cost() + 50D;
}
}
调用:
public class phoneTest {
public static void main(String[] args) {
Phone p1 = new XiaoMi();
p1 = new Battery(p1);
String str = p1.getDescription();
p1.cost();
System.out.println(str + Double.toString(p1.cost()));
}
}
从装饰者模式的理解说JAVA的IO包 http://www.cnblogs.com/coprince/p/6525581.html
适配器模式
适配器模式是一种补偿模式,解决接口不相容,主要场景是修改已经投入使用的项目中的
对象适配器(利用组合)
类适配器(利用继承)
需求:给购物车类添加“根据购物车的东西推荐其他商品的商品”的功能(买了商品的人还买了···)
//商品信息
public class ProductInfo {
private String name;
private String price;
private int amount;
//省略getset
}
//购物车
public class ShopCart {
private ArrayList<ProductInfo> items = new ArrayList<ProductInfo>();
public ArrayList<ProductInfo> placeorder(ProductInfo pdif) {
items.add(pdif);
return items;
}
}
//适配器目标
public interface Target {
//原先的功能
ArrayList<ProductInfo> placeorder(ProductInfo pdif);
//添加的功能
ArrayList<ProductInfo> addLinkedItems();
}
//适配器类(对象适配器)
public class Adapter implements Target {
private ShopCart cart;
private ArrayList<ProductInfo> otherItems = new ArrayList<ProductInfo>();
public Adapter(ShopCart cart) {
this.cart = cart;
}
@Override
public ArrayList<ProductInfo> placeorder(ProductInfo pdif) {
return cart.placeorder(pdif);
}
@Override
public ArrayList<ProductInfo> addLinkedItems() {
//根据关联规则等算法得出具体的ProductInfo,再加入到otherItems
return otherItems;
}
}
//适配器类(类适配器)
class Adapter2 extends ShopCart implements Target {
private ArrayList<ProductInfo> otherItems = new ArrayList<ProductInfo>();
public Adapter2() {
}
@Override
public ArrayList<ProductInfo> placeorder(ProductInfo pdif) {
// TODO Auto-generated method stub
return super.placeorder(pdif);
}
@Override
public ArrayList<ProductInfo> addLinkedItems() {
//根据关联规则等算法得出具体的ProductInfo,再加入到otherItems
return otherItems;
}
}