初学设计模式

来源:互联网 发布:金江软件 编辑:程序博客网 时间:2024/05/07 23:35

在论坛上有个帖子说一道面试题,有30多应徵者没能答对,其题目主要为:写一个桌子类,要求有一个方法求出体积。问题上去很简单,但后来才最后知道那么多人没做对的原因是因为需要用到封装、继续、多态,出题的是有点脑残,真是脱裤子放屁,呵呵。

以下是第一次写简单工厂模式,不过严格来说,这还不是设计模式

using System;

using System.Collections.Generic;

using System.Text;

 

namespace Tabel

{

    class Program

    {

        static void Main(string[] args)

        {

            Tabel tabel;

            tabel = Factory.CreateTable("double");

            Console.WriteLine(tabel.GetVolume());

 

            tabel = Factory.CreateTable("none");

            Console.WriteLine(tabel.GetVolume());

 

            Console.ReadLine();

        }

    }

 

    ///

    /// 桌子

    ///

    class Tabel

    {

        private double length = 0;

        private double width = 0;

        private double height = 0;

        private double result = 0;

 

        public double Result

        {

            get

            {

                return result;

            }

            set

            {

                result = value;

            }

        }

 

        public double Length

        {

            get

            {

                return length;

            }

            set

            {

                length = value;

            }

        }

 

        public double Width

        {

            get

            {

                return width;

            }

            set

            {

                width = value;

            }

        }

 

        public double Height

        {

            get

            {

                return height;

            }

            set

            {

                height = value;

            }

        }

 

        public virtual double GetVolume()

        {

            return Length * Width * Height;

        }

 

    }

 

    ///

    /// 2张桌子

    ///

    class DoubleTable : Tabel

    {

        public override double GetVolume()

        {

            return Length * 2 * Width * Height;

        }

    }

 

    class Factory

    {

        public static Tabel CreateTable(string result)

        {

            Tabel table = null;

            if (result == "double")

            {

                table = new DoubleTable();

                table.Length = 10;

                table.Width = 10;

                table.Height = 10;

                return table;

            }

            else

            {

                table = new Tabel();

                table.Length = 10;

                table.Width = 10;

                table.Height = 10;

                return table;

            }

        }

    }

}

原创粉丝点击