refactor singleton

This commit is contained in:
Lightczx 2024-04-19 17:05:22 +08:00
parent a983ed45ce
commit 820cd8949d
3 changed files with 16 additions and 30 deletions

View File

@ -38,7 +38,7 @@ public class MatchTemplateHelper
if (matchMode is TemplateMatchModes.SqDiff or TemplateMatchModes.CCoeff or TemplateMatchModes.CCorr)
{
Cv2.Normalize(result, result, 0, 1, NormTypes.MinMax, -1, null);
Cv2.Normalize(result, result, 0, 1, NormTypes.MinMax, -1);
}
Cv2.MinMaxLoc(result, out var minValue, out var maxValue, out var minLoc, out var maxLoc);
@ -58,12 +58,12 @@ public class MatchTemplateHelper
}
}
return new Point();
return default;
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
return new Point();
_logger.LogError(ex, ex.Message);
return default;
}
}
@ -83,10 +83,7 @@ public class MatchTemplateHelper
try
{
using var result = new Mat();
if (maskMat == null)
Cv2.MatchTemplate(srcMat, dstMat, result, TemplateMatchModes.CCoeffNormed);
else
Cv2.MatchTemplate(srcMat, dstMat, result, TemplateMatchModes.CCoeffNormed, maskMat);
Cv2.MatchTemplate(srcMat, dstMat, result, TemplateMatchModes.CCoeffNormed, maskMat!);
var mask = new Mat(result.Height, result.Width, MatType.CV_8UC1, Scalar.White);
var maskSub = new Mat(result.Height, result.Width, MatType.CV_8UC1, Scalar.Black);
@ -106,7 +103,7 @@ public class MatchTemplateHelper
}
catch (Exception ex)
{
_logger.LogError("{Ex}", ex);
_logger.LogError(ex, ex.Message);
return points;
}
}

View File

@ -14,7 +14,7 @@ namespace BetterGenshinImpact.GameTask
public class TaskContext
{
private static TaskContext? _uniqueInstance;
private static readonly object InstanceLocker = new();
private static object? InstanceLocker;
private TaskContext()
{
@ -22,15 +22,7 @@ namespace BetterGenshinImpact.GameTask
public static TaskContext Instance()
{
if (_uniqueInstance == null)
{
lock (InstanceLocker)
{
_uniqueInstance ??= new TaskContext();
}
}
return _uniqueInstance;
return LazyInitializer.EnsureInitialized(ref _uniqueInstance, ref InstanceLocker, () => new TaskContext());
}
public void Init(IntPtr hWnd)

View File

@ -1,4 +1,6 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading;
namespace BetterGenshinImpact.Model;
@ -9,18 +11,13 @@ namespace BetterGenshinImpact.Model;
/// <typeparam name="T"></typeparam>
public class Singleton<T> where T : class
{
// 使用Lazy<T>确保线程安全的延迟初始化
private static readonly Lazy<T> _instance = new(() => CreateInstanceOfT()!, isThreadSafe: true);
private static T? _instance;
private static object? syncRoot;
public static T Instance => _instance.Value;
public static T Instance => LazyInitializer.EnsureInitialized(ref _instance, ref syncRoot, CreateInstance);
// 保护的构造函数,防止直接实例化
protected Singleton()
private static T CreateInstance()
{
}
private static T? CreateInstanceOfT()
{
return Activator.CreateInstance(typeof(T), true) as T;
return (T)Activator.CreateInstance(typeof(T), true)!;
}
}