通过共享的方式高效的支持大量细粒度的对象。在有大量对象时,有可能会造成内存溢出,我们把其中共同的部分抽象出来,如果有相同的业务请求,直接返回在内存中已有的对象,避免重新创建。
using System;
using System.Collections.Generic;namespace ConsoleApp1
{public abstract class BikeFlyWeight{// 内部状态protected bool state = false; //false,未借;true:已借protected string bikeId;// 外部状态public abstract void ride(string name);public abstract void back();public bool getState() {return state;}}public class MoBikeFlyWeight : BikeFlyWeight{public MoBikeFlyWeight(string bikeId) {this.bikeId = bikeId;}public override void ride(string name){this.state = true;Console.WriteLine(name + ":借了单车(" + bikeId + ")");}public override void back(){state = false;Console.WriteLine("单车(" + bikeId + "):已还回");}}public class BikeFlyWeightFactory {private static BikeFlyWeightFactory instance = new BikeFlyWeightFactory();private List<BikeFlyWeight> pool = new List<BikeFlyWeight>();public static BikeFlyWeightFactory getInstance(){return instance;}private BikeFlyWeightFactory() {for (int i = 0; i < 2; i++) {pool.Add(new MoBikeFlyWeight(i + "号"));}}public BikeFlyWeight getBike(){foreach (BikeFlyWeight bike in pool){if (!bike.getState()){return bike;}}return null;}}class Program{static void Main(string[] args){BikeFlyWeightFactory factory = BikeFlyWeightFactory.getInstance();BikeFlyWeight bike1 = factory.getBike();bike1.ride("张珊");BikeFlyWeight bike2 = factory.getBike();bike2.ride("李思");bike1.back();BikeFlyWeight bike3 = factory.getBike();bike3.ride("王武");BikeFlyWeight bike4 = factory.getBike();if (bike4 != null){bike4.ride("周柳");}else{Console.WriteLine("无单车可借");}}}
}