設計模式----------策略模式

策略模式,不講過多的廢話。咱們來直接看代碼。java

一、咱們先定一個接口ide

package com.guoguo.celvemoshi;
/**
 * 定義一個策略接口
 * @author 蟈蟈
 *
 */
public interface StrategyService {
    //定義一個可執行方法
    public void execute();
}

二、策略的具體實現(java多態---不懂先去了解多態的使用)this

package com.guoguo.celvemoshi;

/**
 * 第一個策略
 * @author 蟈蟈
 *
 */
public class CelveOneServiceImpl implements StrategyService{

    @Override
    public void execute() {
        System.err.println("執行策略一");
    }

}
package com.guoguo.celvemoshi;

/**
 * 第二個策略
 * @author 蟈蟈
 *
 */
public class CelveTwoServiceImpl implements StrategyService {

    @Override
    public void execute() {
        // TODO Auto-generated method stub
        System.err.println("執行策略二");
    }

}
package com.guoguo.celvemoshi;
/**
 * 第三個策略
 * @author 蟈蟈
 *
 */
public class CelveThreeServiceImpl implements StrategyService {

    @Override
    public void execute() {
        // TODO Auto-generated method stub
        System.err.println("執行策略三");
    }

}

三、策略定好以後,須要有個地方存放這些策略,以便在不一樣的狀況下方便使用spa

package com.guoguo.celvemoshi;

public class Context {
    private StrategyService straService;
    //定義構造方法
    public Context(StrategyService straService){
        this.straService = straService;
    }
    //定義一個執行方法,去執行對應的策略
    public void execute() {
        this.straService.execute();
    }
    
}

四、策略的使用code

package com.guoguo.celvemoshi;

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Context context;
        //在不一樣的狀況下使用不一樣的策略,咱們先使用策略三
        context = new Context(new CelveThreeServiceImpl());
        context.execute();
        
        // 在不一樣的狀況下使用不一樣的策略,咱們先使用策略二
        context = new Context(new CelveTwoServiceImpl());
        context.execute();

        // 在不一樣的狀況下使用不一樣的策略,咱們先使用策略一
        context = new Context(new CelveOneServiceImpl());
        context.execute();
        
    }

}
相關文章
相關標籤/搜索