第103回 Strategyパターンについて

公開日:2014-10-22 更新日:2019-05-11

1. 概要

独り言によるプログラミング講座「第103回 Strategyパターンについて」です。
デザインパターンの1つである Strategy パターンについて説明しています。

2. 動画



3. 動画中に書いたソース

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //★独り言によるプログラミング講座

            //■Strategyパターンについて
            //  動的に機能を変更するパターン
            //  ハードとソフト
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int result = Calc.calc(new Sub(), 200, 100);
            MessageBox.Show(result.ToString());
        }
    }

    //ソフト
    interface ICalc {
        int calc(int a, int b);
    }

    class Add : ICalc {
        public int calc(int a, int b) {
            return a + b;
        }
    }

    class Sub : ICalc {
        public int calc(int a, int b) {
            return a - b;
        }
    }

    //ハード
    class Calc {
        public static int calc(ICalc obj, int a, int b) {
            return obj.calc(a, b);
        }

        /*
        public int add(int a, int b) {
            return a + b;
        }
        public int sub(int a, int b) {
            return a - b;
        }
        public int mul(int a, int b) {
            return a * b;
        }
        public int div(int a, int b) {
            return a / b;
        }
        */

    }
}