设计模式_策略模式

策略模式

介绍

设计模式定义案例问题堆积在哪里解决办法
策略模式对算法进现封装,抽象
如:IF elseIF 一大堆
可以配合工厂模式使用
炼丹炉里做饭
要求 菜谱 和 食材可配置
问题在可配置
菜谱
封装菜谱
然后抽象菜谱,为了统一使用方法

类图

CaiPuBase 抽象菜谱

CaiPuA 菜谱A

CaiPuB 菜谱B

CaiPuC 菜谱C

LianDanLu 炼丹炉

代码

CaiPuBase

using System.Collections.Generic;

/// <summary>
/// 菜谱
/// </summary>
public abstract class CaiPuBase
{
    public abstract string Create(List<string> foodList);
}

CaiPuA

using System.Collections.Generic;

public class CaiPuA : CaiPuBase
{
    string funName = "炒";

    public override string Create(List<string> elementList)
    {
        string result;
        result = funName + ":";
        foreach (var item in elementList)
        {
            result += item;
        }

        return result;
    }
}

CaiPuB

using System.Collections.Generic;

public class CaiPuB : CaiPuBase
{
    string funName = "蒸";

    public override string Create(List<string> elementList)
    {
        string result;
        result = funName + ":";
        foreach (var item in elementList)
        {
            result += item;
        }

        return result;
    }
}

CaiPuC 

using System.Collections.Generic;

public class CaiPuC : CaiPuBase
{
    string funName = "煮";

    public override string Create(List<string> elementList)
    {
        string result;
        result = funName + ":";
        foreach (var item in elementList)
        {
            result += item;
        }

        return result;
    }
}

LanDanLu

using System.Collections.Generic;

/// <summary>
/// 炼丹炉
/// </summary>
public class LianDanLu
{
    public string GetFood(CaiPuBase caiPu, List<string> elementList)
    {
        return caiPu.Create(elementList);
    }
}

测试代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestCL : MonoBehaviour
{
    void Start()
    {
        LianDanLu ldl = new LianDanLu();

        {
            List<string> list = new List<string>
            {
                "萝卜",
                "鸡蛋"
            };
            string food = ldl.GetFood(new CaiPuA(), list);
            Debug.Log(food);
        }

        {
            List<string> list = new List<string>
            {
                "萝卜",
                "鸡蛋"
            };
            string food = ldl.GetFood(new CaiPuB(), list);
            Debug.Log(food);
        }

        {
            List<string> list = new List<string>
            {
                "萝卜",
                "鸡蛋"
            };
            string food = ldl.GetFood(new CaiPuC(), list);

            // show
            Debug.Log(food);
        }

    }
}

结果

总结

函数抽象出变量
类抽象出行为

单一的模式很简单 ,难的是从整体出发一步一模式,把细节一直推迟到配置文件/Excel。
多做进行大项目的开发还是很有好处的!
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值