【设计模式】11.享元模式

说明:结构型的,大概就是共享一个对象,重复使用时不用一直创建,达到减少实例化的数量,和内存空间。

要点:用hashtable或者Dictionary来存储对象,有享元工厂管理,抽象类,实现类。

实现:

public class carFactory
    {
        Hashtable hashtable1 = new Hashtable();
        public carFactory()
        {
            hashtable1.Add("A", new car());
            hashtable1.Add("B", new car());
            hashtable1.Add("C", new car());

           
        }

        public ABS_car getobject(string num)
        {
            return (ABS_car)hashtable1[num];
        }
    }


    public abstract class ABS_car
    {
        public abstract void run();
    }

    public class car : ABS_car
    {
        public override void run()
        {
            //实现方法
        }
    }

    public class test
    {
        public void start()
        {
            carFactory cf = new carFactory();
            ABS_car c = cf.getobject("A");
        }
    }
原文地址:https://www.cnblogs.com/laokchen/p/13541101.html