记录一下写的设计模式
关键技术点
1 用spring依赖注入代替了工厂,新加不需要添加类
2 用策略解决了添加业务只需要添加相应策略类,开放封闭原则
具体代码
1 Item 具体的商品,有名字和价钱
public class Item {
private String des;
private int cents;
public Item(String des, int cents) {
this.des = des;
this.cents = cents;
}
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
public int getCents() {
return cents;
}
public void setCents(int cents) {
this.cents = cents;
}
}
2 Bill商品的列表,用于放商品
import java.util.ArrayList;
import java.util.List;
public class Bill {
private List<Item> items = new ArrayList<Item>();
public void addItem(Item item){
items.add(item);
}
public void removeItem(Item item){
items.remove(item);
}
public int getSumCents(){
return items.stream().mapToInt(item -> item.getCents()).sum();
}
public void pay(PaymentMethod paymentMethod){
paymentMethod.pay(getSumCents());
}
}
3 PaymentMethod 支付接口,将支付抽象出来
public interface PaymentMethod {
void pay(int cents);
}
4 Card 抽象类
import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public abstract class Card implements PaymentMethod {
static Map<String,PaymentMethod> paymentMethodMap = new ConcurrentHashMap<>();
@PostConstruct
public void init(){
paymentMethodMap.put(getType(),this);
}
public void pay(int cents) {
System.out.println("use"+getType()+"->payesd"+cents+"cents");
excectuTransaction(cents);
}
protected abstract String getType();
protected abstract void excectuTransaction(int cents);
}
5 CreditCard 和DebitCard具体两个实现策略
import org.springframework.stereotype.Service;
@Service
public class DebitCard extends Card {
protected String getType() {
return "debit";
}
protected void excectuTransaction(int cents) {
System.out.println("debit支付:"+cents);
}
}
import org.springframework.stereotype.Service;
@Service
public class CreditCard extends Card {
protected String getType() {
return "credit";
}
protected void excectuTransaction(int cents) {
System.out.println("CreditCard结账:"+cents);
}
}
6 工厂
public class PaymentMethodFatory {
public static PaymentMethod getPaymentMethod(String type){
switch (type){
case "credit":
return new CreditCard();
case "debit":
return new DebitCard();
default:throw new RuntimeException("cant find type");
}
}
}
7main方法
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class StrategyDemo {
public static void main(String[] args) {
Bill bill = new Bill();
bill.addItem(new Item("书1",100));
bill.addItem(new Item("书2",200));
// bill.pay(PaymentMethodFatory.getPaymentMethod("d"));
ClassPathXmlApplicationContext context = new
ClassPathXmlApplicationContext("applicationContext.xml");
context.start();
bill.pay(Card.paymentMethodMap.get("credit"));
}
}