• 原型模式


    故事:

      鞋子厂来了一个订单,需要一批(2双)运动鞋和一批(2双)休闲鞋。需要同样鞋码,但颜色不一样。

      于是,老板决定使用同样的鞋模来生产小样,然后染色。

    建模:

      鞋子模型(原型) ——》 定码

      运动鞋 ——》染色

      休闲鞋 ——》染色

    类图:

    实现:

    Shoes

    namespace Prototype
    {
        public abstract class Shoes
        {
            public int size;
            protected string color;       
            public string Color
            {
                set
                {
                    color = Color;
                }
                get
                {
                    return color;
                }
            }
            public int Size
            {
                set
                {
                    size = Size;
                }
                get
                {
                    return size;
                }
            }
            public abstract Shoes Clone(string color);
        }
    }

    SportShoes

    namespace Prototype
    {
        class SportShoes:Shoes
        {
            public SportShoes(int size,string color)
            {
                this.size = size;
                this.color = color;
            }
    
            public override Shoes Clone(string color)
            {
                return new SportShoes(this.size,color);
            }
        }
    }

    LeisureShoes

    namespace Prototype
    {
        class LeisureShoes: Shoes
        {
            bool indoor;
            public LeisureShoes(int size, string color, bool indoor)
            {
                this.size = size;
                this.color = color;
                this.indoor = indoor;
            }
    
            public override Shoes Clone(string color)
            {
                return new LeisureShoes(this.size, color, this.indoor);
            }
        }
    }

    Program

    namespace Prototype
    {
        class Program
        {
            static void Main(string[] args)
            {
                SportShoes shoes = new SportShoes(43,"Red");     
                SportShoes secondShoes = (SportShoes)shoes.Clone("Black");
    
                LeisureShoes leisureShoes = new LeisureShoes(39, "Black", true);
                LeisureShoes secondLeisureShoes = (LeisureShoes)leisureShoes.Clone("White");
    
                ArrayList al = new ArrayList();
                al.Add(shoes);
                al.Add(secondShoes);
                al.Add(leisureShoes);
                al.Add(secondLeisureShoes);
    
                foreach (Shoes i in al)
                {
                    Console.WriteLine("Size:{0},Color:{1}", i.Size, i.Color);
                }
            }
        }
    }

    效果:

  • 相关阅读:
    杨老师课堂_VBA学习教程之一键合并所有文件
    无题
    杨老师课堂_VBA学习教程之VBA中使用函数
    杨老师课堂_Java核心技术下之控制台模拟文件管理器案例
    杨老师课堂之JavaScript定时器_农夫山泉限时秒杀案例
    交换机级联,堆叠,集群技术介绍
    IP划分
    光纤
    交换机
    URL中“#” “?” &“”号的作用
  • 原文地址:https://www.cnblogs.com/jiejue/p/2711813.html
Copyright © 2020-2023  润新知