CSharp设计模式读书笔记(1):简单工厂模式(学习难度:★★☆☆☆,使用频率:★★★☆☆)

Simple Factory模式实际上不是GoF 23个设计模式中的一员。

模式角色与结构:

示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharp.DesignPattern.SimpleFactoryPattern
{
    class Program // 类的修饰符有public和internal, 默认是internal
    {
        static void Main(string[] args)
        {
            SimpleFactory factory = new SimpleFactory();

            IAthlete footballAthlete = factory.Create("Football");
            IAthlete basketballAthlete = factory.Create("Baseketball");

            footballAthlete.Run();
            footballAthlete.Jump();

            basketballAthlete.Run();
            basketballAthlete.Jump();

            Console.ReadLine();
        }
    }

    interface IAthlete // 接口的修饰符有public和internal, 默认是internal
    {
        void Run(); // 接口成员默认修饰符为public,但是不能显式添加public
        void Jump();
    }

    class FootballAthlete : IAthlete
    {
        public void Run()
        {
            Console.WriteLine("FootballAthlete Run...");
        }

        public void Jump()
        {
            Console.WriteLine("FootballAthlete Jump...");
        }
    }

    class BaseketballAthlete : IAthlete
    {
        public void Run()
        {
            Console.WriteLine("BaseketballAthlete Run...");
        }

        public void Jump()
        {
            Console.WriteLine("BaseketballAthlete Jump...");
        }
    }

    class SimpleFactory
    {
        public IAthlete Create(String athleteType)
        {
            if (athleteType == "Baseketball")
            {
                return new BaseketballAthlete();
            }
            else if (athleteType == "Football")
            {
                return new FootballAthlete();
            }
            else
            {
                return null;
            }
        }
    }
}
原文地址:https://www.cnblogs.com/thlzhf/p/2791454.html