享元模式(Flyweight Pattern)主要用于减少创建对象的数量,以减少内存占用和提高性能。
享元模式尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。
意图:运用共享技术有效地支持大量细粒度的对象。
主要解决:在有大量对象时,有可能会造成内存溢出,我们把其中共同的部分抽象出来,如果有相同的业务请求,
直接返回在内存中已有的对象,避免重新创建。
何时使用: 1、系统中有大量对象。 2、这些对象消耗大量内存。 3、这些对象的状态大部分可以外部化。
4、这些对象可以按照内蕴状态分为很多组,当把外蕴对象从对象中剔除出来时,每一组对象都可以用一个对象来代替。
5、系统不依赖于这些对象身份,这些对象是不可分辨的。
如何解决:用唯一标识码判断,如果在内存中有,则返回这个唯一标识码所标识的对象。
关键代码:用 HashMap 存储这些对象。
优点:大大减少对象的创建,降低系统的内存,使效率提高。
缺点:提高了系统的复杂度,需要分离出外部状态和内部状态,而且外部状态具有固有化的性质,
不应该随着内部状态的变化而变化,否则会造成系统的混乱。
使用场景: 1、系统有大量相似对象。 2、需要缓冲池的场景。
注意事项: 1、注意划分外部状态和内部状态,否则可能会引起线程安全问题。 2、这些类必须有一个工厂对象加以控制。
内部状态:在享元对象的内部并且不会随着环境的改变而改变的共享部分
外部状态:随环境改变而改变的,不可以共享的状态。
涉及的角色如下几种角色:
抽象享元角色(Flyweight):此角色是所有的具体享元类的基类,为这些类规定出需要实现的公共接口。
具体享元角色(ConcreteFlyweight):实现抽象享元角色所规定的接口。如果有内部状态的话,可以在类内部定义。
享元工厂角色(FlyweightFactory):本角色复杂创建和管理享元角色。
本角色必须保证享元对象可以被系统适当地共享,当一个客户端对象调用一个享元对象的时候,
享元工厂角色检查系统中是否已经有一个符合要求的享元对象,如果已经存在,享元工厂角色就提供已存在的享元对象,
如果系统中没有一个符合的享元对象的话,享元工厂角色就应当创建一个合适的享元对象。
客户端角色(Client):本角色需要存储所有享元对象的外部状态。
该实例基于WPF实现,直接上代码,下面为三层架构的代码。
一 Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 设计模式练习.Model.享元模式
{
//1,基础接口类
public interface Animal
{
void run();
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 设计模式练习.Model.享元模式
{
//3,创建工厂,用于生成实体类的对象
public class AnimalFactory
{
private static Dictionary<string, Animal> Animals = new Dictionary<string, Animal>();
private AnimalFactory() { }
public static Animal GetDog(string name)
{
Dog dog = null;
if (Animals.ContainsKey(name))
{
dog = Animals[name] as Dog;
}
else
{
dog = new Dog(name);
Animals.Add(name, dog);
}
return dog;
}
public static void remove(string name)
{
if (Animals.ContainsKey(name))
{
Animals.Remove(name);
}
}
public static void removeLast()
{
if (Animals.Count > 0)
{
string index = string.Empty;
foreach (string item in Animals.Keys)
{
index = item;
}
if (index != string.Empty)
{
Animals.Remove(index);
}
}
}
public static void removeFirst()
{
if (Animals.Count > 0)
{
string index = string.Empty;
foreach (string item in Animals.Keys)
{
index = item;
break;
}
if (index != string.Empty)
{
Animals.Remove(index);
}
}
}
public static int getObjectCount()
{
return Animals.Count;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 设计模式练习.Model.享元模式
{
//2,实现接口类
internal class Dog : Animal
{
public Dog(string name)
{
Name = name;
}
public string Name { get; set; }
public int Age { get; set; }
public string Hubby { get; set; }
public string RunInfo { get; set; }
public void run()
{
RunInfo = $"name:{Name},age:{Age},hubby:{Hubby}";
}
}
}
二 View
<Window x:Class="设计模式练习.View.享元模式.EnjoyYuan"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:设计模式练习.View.享元模式"
mc:Ignorable="d"
Title="EnjoyYuan" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Content="对象数量:" FontSize="30" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<Label Content="对象信息:" FontSize="30" VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Row="1"/>
<Button Content="删除对象" Grid.Row="2" FontSize="30" Command="{Binding removeCommand}"/>
<Button Content="增加对象" Grid.Row="2" Grid.Column="1" FontSize="30" Command="{Binding addCommand}"/>
<Label Content="{Binding Count}" Grid.Row="0" Grid.Column="1"/>
<RichTextBox x:Name="log" Grid.Row="1" Grid.Column="1" VerticalScrollBarVisibility="Visible" >
<RichTextBox.Document>
<FlowDocument>
<Paragraph>
<Run Text="{Binding Info}"/>
</Paragraph>
</FlowDocument>
</RichTextBox.Document>
</RichTextBox>
</Grid>
</Window>
三 ViewModel
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 设计模式练习.Model.享元模式;
using 设计模式练习.View.享元模式;
namespace 设计模式练习.ViewModel.享元模式
{
partial class EnjoyYuan_ViewModel : ObservableObject
{
private string[] animals = { "汤姆", "柯基", "泰勒", "发那科", "哈佛", "清华", "丽君", "东东", "爱爱", "科莱" };
[ObservableProperty]
private int count;
[ObservableProperty]
private string info;
[RelayCommand]
private void add()
{
int i = new Random().Next(0, animals.Length);
Dog dog = AnimalFactory.GetDog(animals[i]) as Dog;
dog.Name = animals[i];
dog.Age = 18;
dog.Hubby = "吃饭";
Count = AnimalFactory.getObjectCount();
dog.run();
Info += dog.RunInfo + "\r\n";
}
[RelayCommand]
private void remove()
{
AnimalFactory.removeFirst();
Count = AnimalFactory.getObjectCount();
}
}
}