Provider模式应用demo
Posted zhiyong-itnote
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Provider模式应用demo相关的知识,希望对你有一定的参考价值。
参考ObjectPool对象池设计原理还原一个简易的Provider模式。
using System;
using System.Dynamic;
using System.Reflection.Metadata.Ecma335;
using System.Threading;
using System.Xml;
namespace ProviderPattern
{
/// <summary>
/// 目标
/// </summary>
/// <typeparam name="T"></typeparam>
public class TargetClass<T> where T:class
{
private ObjectWrapper[] _items;
private ITargetClassPolicy<T> _policy;
public TargetClass(ITargetClassPolicy<T> policy)
{
_policy = policy;
_items = new ObjectWrapper[3];
}
public T Get()
{
var items = _items;
for (var i = 0; i < items.Length; i++)
{
var item = items[i].Element;
if (item != null && Interlocked.CompareExchange(ref items[i].Element, null,item) != null)
{
return item;
}
}
return Create();
}
public void Return(T obj)
{
if (!_policy.Return(obj))
{
return;
}
var items = _items;
for (var i = 0; i < items.Length && Interlocked.CompareExchange(ref items[i].Element, obj, null) != null; ++i)
{
}
}
private T Create() => _policy.Create();
private struct ObjectWrapper
{
public T Element;
}
}
/// <summary>
/// Provider 提供者
/// </summary>
public class TargetClassProvider
{
public TargetClass<T> Create<T>(ITargetClassPolicy<T> policy) where T : class, new()
{
return new TargetClass<T>(policy);
}
}
/// <summary>
/// Policy 策略 规范
/// </summary>
/// <typeparam name="T"></typeparam>
public interface ITargetClassPolicy<T>
{
T Create();
bool Return(T obj);
}
/// <summary>
/// Policy 具体策略类
/// </summary>
/// <typeparam name="T"></typeparam>
public class TargetClassPolicy<T> : ITargetClassPolicy<T> where T : class, new()
{
public T Create()
{
return new T();
}
public bool Return(T obj)
{
return true;
}
}
class User
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
var target = new TargetClass<User>(new TargetClassPolicy<User>());
var get = target.Get();
Console.WriteLine($"{get.Name},{get.Age}");
var user1 = new User()
{
Age = 18,
Name = "MicroHeart"
};
var user2 = new User()
{
Age = 19,
Name = "MicroHeart"
};
var user3 = new User()
{
Age = 20,
Name = "MicroHeart"
};
target.Return(user1);
target.Return(user2);
target.Return(user3);
var get1 = target.Get();
Console.WriteLine($"{get1.Name},{get1.Age}");
var get2 = target.Get();
Console.WriteLine($"{get2.Name},{get2.Age}");
Console.Read();
}
}
}
存储对象的数组ObjectWrapper内元素的取、还操作通过Interlock.CompareExchange巧妙的实现,并且是线程安全的。
取操作:Interlocked.CompareExchange(ref items[i].Element, null,item)
。取完后将元素置为null
还操作:Interlocked.CompareExchange(ref items[i].Element, obj, null)
如果元素为null,则赋值
设计原理:通过Policy构建Provider,通过Provider创建最终的目标类(target)。
参考链接:ObjectPool 对象池设计模式
以上是关于Provider模式应用demo的主要内容,如果未能解决你的问题,请参考以下文章
Motan在服务provider端用于处理request的线程池
Pipeline模式与Factory+Provider模式的应用
如何解决缩小代码中的 Angular JS Unknown Provider 错误
slim.dataset_data_provider.DatasetDataProvider with num_epochs=1 抛出错误