设计模式笔记(附部分java代码)

首先,先了解UML图标的一些含义,也可作为查询的工具

UML:

http://blog.csdn.net/linzhiji/archive/2010/12/02/6051254.aspx

https://www.runoob.com/design-pattern/design-pattern-tutorial.html

设计模式:

合成模式(Composite Pattern)

外观模式(Facade Pattern)

public class CPU{
    public void startup(){
        System.out.println("cpu startup");    
    }

    public void shutdown(){
        System.out.println("cpu shutdown");
    }
}
public class Memory{
    public void startup(){
        System.out.println("Memory startup");
    }

    public void shutdown(){
        System.out.println("Memory shutdown");
    }

}
public Computer{
    private CPU cpu;
    private Memory memory;

    public Computer(){
        this.cpu = new CPU();
        this.memory = new Memory();
    }

    public void startup(){
        System.out.println("start computer");
        this.cpu.startup();
        this.memory.startup();
        System.out.println("start computer-finish");
    }

    public void shutdown(){
        System.out.println("Shutdown computer");
        this.cpu.shutdown();
        this.cpu.shutdown();
        System.out.println("Shutdown computer-finish");
    }
}

Java设计模式之——Adapter(适配器模式)

电脑通过USB读取数据,鼠标接USB,SD卡不能直接插USB,需要加个读卡器插入到USB上

interface USB{
    public void use();
}

class mouseUSB implements USB{
    @Override
    public void use(){
        System.out.println("mouse is using");
    }
}

interface SDCard{
    public void readSDCard();
}

class SDCardHandle implements SDCard{
    @Override
    public void readSDCard(){
        System.out.println("SDCard reading");
    }
}

class SDCardAdapter extends SDCardHandle implements USB{
    @Override
    public void use(){
        super.readSDCard();
    }
}

class SDCardAdaper2 implements USB{
    private SDCardHandle sdCardHandle;

    public SDCardAdaper2(SDCardHandle sdCardHandle){
        this.sdCardHandle = sdCardHandle;
    }

    @Override
    public void use(){
        this.sdCardHandle.readSDCard();
    }
}


@SpringBootTest
public class AdapterTest {

    @Test
    void sdcardTest(){
        USB usb = new mouseUSB();
        usb.use();

        // 类adapter
        USB usb1 = new SDCardAdapter();
        usb1.use();

        // 对象adapter
        SDCardHandle sdCardHandle = new SDCardHandle();
        USB usb2 = new SDCardAdaper2(sdCardHandle);
        usb2.use();
    }
}

工厂模式

interface Shape{
    void draw();
}

class Circle implements Shape{
    @Override
    public void draw(){
        System.out.println("Draw circle");
    }
}

class Rectangle implements Shape{
    @Override
    public void draw(){
        System.out.println("Draw rectangle");
    }
}

class FactoryShape{
    public Shape createShap(String type){

        Shape shape = null;
        if("Circle".equals(type)){
            shape = new Circle();
        }else if("Rectangle".equals(type)){
            shape = new Rectangle();
        }

        return shape;
    }
}

@SpringBootTest
public class FactoryImplTest {
    
    @Test
    void shapeTest(){
        FactoryShape factoryShape = new FactoryShape();
        Shape shape = factoryShape.createShap("Circle");
        if(shape != null)
            shape.draw();

        shape = factoryShape.createShap("Rectangle");
        if(shape != null)
            shape.draw();
    }
}

单例模式

class SingleObject{
    private static volatile SingleObject singleObject = new SingleObject();

    private SingleObject(){

    }

    static public SingleObject  getInstance(){

        if(null == singleObject){
            synchronized(SingleObject.class){
                singleObject = new SingleObject();
            }
        }

        return singleObject;
    }

    public void showMessage(){
        System.out.println("show singleton message");
    }
}

@SpringBootTest
public class SingletonImplTest {

    @Test
    void singleTest(){
        SingleObject singleObject = SingleObject.getInstance();
        singleObject.showMessage();
        singleObject.showMessage();
    }
}

责任链模式

一文带你玩转设计模式之「责任链」

abstract class Chain{
    int level;
    public Chain nextHandle;

    public Chain(int level){
        this.level = level;
    }
    
    public final void handleChain(int level){
        if(this.level == level){
            handleOrder();
        }else{
            if(nextHandle != null){
                nextHandle.handleOrder();
            }
        }
    }

    public abstract void handleOrder();
}

// 订单折扣活动处理
class DiscountOrder extends Chain{

    public DiscountOrder(int level){
        super(level);
    }

    @Override
    public void handleOrder(){
        System.out.println("handle discountOrder");
    }
}

// 订单优惠券处理
class CouponOrder extends Chain{

    public CouponOrder(int level){
        super(level);
    }

    @Override
    public void handleOrder(){
        System.out.println("handle couponOrder");
    }
}


@SpringBootTest
public class ChainTest {
    @Test
    void chainTest(){

        Chain discountOrder = new DiscountOrder(1);
        Chain couponOrder = new CouponOrder(2);

        discountOrder.nextHandle = couponOrder;

        Chain chain = discountOrder;

        chain.handleChain(1);
        chain.handleChain(2);
    }
}

状态模式

// 状态:已投币,未投币,商品售罄
// 动作:投币,退钱,出货

interface State{
    //投币
    public void insertMoney();
    //退钱
    public void backMoney();
    //出货
    public void sellGoods();
}


class GoodsMachine{

    HasMoneyState hasMoneyState;
    NoMoneyState noMoneyState;
    SoldOutState soldOutState;
    State state = soldOutState;

    // 商品库存
    int count = 0;

    public GoodsMachine(int count){
        this.hasMoneyState = new HasMoneyState(this);
        this.noMoneyState = new NoMoneyState(this);
        this.soldOutState = new SoldOutState(this);

        this.count = count;
        if(count > 0){
            this.state = noMoneyState;
        }
    }

    public void insertMoney(){
        state.insertMoney();
    }

    public void soldGood(){
        state.sellGoods();
    }

    public void backMoney(){
        state.backMoney();
    }

    public HasMoneyState getHasMoneyState() {
        return hasMoneyState;
    }

    public void setHasMoneyState(HasMoneyState hasMoneyState) {
        this.hasMoneyState = hasMoneyState;
    }

    public NoMoneyState getNoMoneyState() {
        return noMoneyState;
    }

    public void setNoMoneyState(NoMoneyState noMoneyState) {
        this.noMoneyState = noMoneyState;
    }

    public SoldOutState getSoldOutState() {
        return soldOutState;
    }

    public void setSoldOutState(SoldOutState soldOutState) {
        this.soldOutState = soldOutState;
    }

    public State getState() {
        return state;
    }

    public void setState(State state) {
        this.state = state;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}


class HasMoneyState implements State{

    GoodsMachine goodsMachine;

    public HasMoneyState(GoodsMachine goodsMachine){
        this.goodsMachine = goodsMachine;
    }

    @Override
    public void insertMoney(){
        System.out.println("已经投币了,不能重复投币");
    }

    @Override
    public void backMoney(){
        System.out.println("退款成功");
        this.goodsMachine.setState(goodsMachine.getNoMoneyState());

    }

    @Override
    public void sellGoods(){
        System.out.println("准备出货了");
        goodsMachine.setCount(goodsMachine.getCount() - 1);
        if(goodsMachine.getCount() > 0){
            System.out.println("出货完成");
            goodsMachine.setState(goodsMachine.getNoMoneyState());
        }else{
            System.out.println("出货完成,货品售罄");
            goodsMachine.setState(goodsMachine.getSoldOutState());
        }
    }
}

class NoMoneyState implements State{
    GoodsMachine goodsMachine;

    public NoMoneyState(GoodsMachine goodsMachine){
        this.goodsMachine = goodsMachine;
    }

    @Override
    public void insertMoney() {
        System.out.println("收到钱了");
        goodsMachine.setState(goodsMachine.getHasMoneyState());
    }

    @Override
    public void backMoney() {
        System.out.println("没投币,没钱可退");
    }

    @Override
    public void sellGoods() {
        System.out.println("没投币,没法出货");
    }
}


class SoldOutState implements State{
    GoodsMachine goodsMachine;

    public SoldOutState(GoodsMachine goodsMachine){
        this.goodsMachine = goodsMachine;
    }


    @Override
    public void insertMoney() {
        System.out.println("商品售罄了,不能投币");
    }

    @Override
    public void backMoney() {
        System.out.println("商品售罄了,不能投币");
    }

    @Override
    public void sellGoods() {
        System.out.println("商品售罄了,不能投币");
    }
}

@SpringBootTest
public class StateTest {
    @Test
    public void  stateTest(){
        GoodsMachine goodsMachine = new GoodsMachine(3);

        goodsMachine.insertMoney();
        goodsMachine.backMoney();

        goodsMachine.insertMoney();
        goodsMachine.insertMoney();

        goodsMachine.soldGood();

        goodsMachine.soldGood();

        goodsMachine.insertMoney();
        goodsMachine.soldGood();

        goodsMachine.insertMoney();
        goodsMachine.soldGood();

        goodsMachine.soldGood();
    }
}

策略模式


abstract class RewardStrategy {
    public abstract int reward();
}

class NewUserRewardStrategy extends RewardStrategy {
    @Override
    public int reward() {
        return 10;
    }
}

class OldUserRewardStrategy extends RewardStrategy {
    @Override
    public int reward() {
        return 1;
    }
}

class RewardContext {
    private RewardStrategy rewardStrategy;

    public RewardStrategy getRewardStrategy() {
        return rewardStrategy;
    }

    public void setRewardStrategy(RewardStrategy rewardStrategy) {
        this.rewardStrategy = rewardStrategy;
    }


    public RewardContext(RewardStrategy strategy) {
        this.rewardStrategy = strategy;
    }

    public RewardContext(){

    }

    public void doStrategy() {
        int rewardMoney = rewardStrategy.reward();
        System.out.println("rewardMoney" + rewardMoney);
    }
}

@SpringBootTest
class StrategyTests {

    @Test
    void testReward(){

        RewardContext rewardContext = new RewardContext();

        NewUserRewardStrategy newUserRewardStrategy = new NewUserRewardStrategy();
        rewardContext.setRewardStrategy(newUserRewardStrategy);

        rewardContext.doStrategy();

        OldUserRewardStrategy oldUserRewardStrategy = new OldUserRewardStrategy();
        rewardContext.setRewardStrategy(oldUserRewardStrategy);

        rewardContext.doStrategy();
    }
}

代理模式

interface Stock{
    public void sell();
}

class ChinaStock implements Stock{

    @Override
    public void sell(){
        System.out.println("sell chinaStock");
    }
}

class StockProxy implements Stock{
    Stock stock;

    public StockProxy(Stock stock){
        this.stock = stock;
    }

    @Override
    public void sell(){
        if(stock != null)
            stock.sell();
    }
}

@SpringBootTest
public class PorxyDemo {
    @Test
    void proxyTest(){
        ChinaStock stock = new ChinaStock();
        StockProxy stockProxy = new StockProxy(stock);
        stockProxy.sell();
    }
}

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页