002、策略模式

一、UML图

        Context:上下文角色,屏蔽上层模块对下层策略、算法的直接访问,封装算法的多变性。
        Strategy:抽象策略角色,对策略的抽象。
        ConcreteStrategy:具体策略类,算法的具体实现,继承或实现Strategy。

二、实例

1、Context

package com.designPattern.strategy;

/**
 * Created by ZhangJintao on 2020/3/8.
 */
public class TransportationContext {
    private Transportation transportation;

    public TransportationContext(Transportation transportation) {
        this.transportation = transportation;
    }

    public void showTransportation(){
        this.transportation.show();
    }
}

2、 Strategy

package com.designPattern.strategy;

/**
 * Created by ZhangJintao on 2020/3/8.
 */
public abstract class Transportation {
    public abstract void show();
}

3、ConcreteStrategy

package com.designPattern.strategy;

/**
 * Created by ZhangJintao on 2020/3/8.
 */
public class ByBicycle extends Transportation {
    @Override
    public void show() {
        System.out.println("我是自行车,健康环保。绿色出行,从我做起。");
    }
}
package com.designPattern.strategy;

/**
 * Created by ZhangJintao on 2020/3/8.
 */
public class ByCar extends Transportation {
    @Override
    public void show() {
        System.out.println("我是小汽车,百公里只需6个油。想去哪里就去哪里,欧耶!");
    }
}

4、main

package com.designPattern.strategy;

/**
 * Created by ZhangJintao on 2020/3/8.
 */
public class main {
    public static void main(String[] args) {
        TransportationContext transportationContext = new TransportationContext(new ByBicycle());
        transportationContext.showTransportation();

        transportationContext = new TransportationContext(new ByCar());
        transportationContext.showTransportation();
    }
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值