用设计模式处理常见的编程问题
这些指导方针的焦点在于执行一个单独的类实例。列表A中的C#代码定义了一个应用单态模式的类。列表B中为对应的VB.NET代码。
列表A
列表A
列表Bnamespace Patterns ...{
public sealed class Singleton ...{
private static readonly Singleton instance = new Singleton();
private int count;
private Singleton() ...{ }
public static Singleton Instance ...{
get ...{
return instance;
} }
public int Count ...{
get ...{ return count++; }
} } }
Public Class SingletonClass Singleton
Private Shared ReadOnly _instance As Singleton = New Singleton()
Private _count As Integer
Private Sub New()Sub New()
End Sub
Public Shared ReadOnly Property Instance()Property Instance() As Singleton
Get
Return _instance
End Get
End Property
Public ReadOnly Property Count()Property Count() As Integer
Get
Return (_count + 1)
End Get
End Property
End Class
关于此类的几点提示:
1.构造器是专用的,因此无法访问,所以用它也不能建立实例。
2.通用实例方法可访问对象实例。它通过包含实例的静态变量返回对象的唯一实例。
3.类的密封声明具有很强的破坏力。密封类用来限制面向对象编程的继承功能。一旦一个类被定义为密封类,此类就不能被继承。
4.计算器变量为专用变量,可通过通用方法进行访问。由于该类只有一个实例,所以该计算器也只有一个实例。
可用几种不同的方法给单态模式编码。上面的列表中应用的是一个实例静态对象,它总是存在。如果该对象从未使用,就会形成管理费用。因此,你可以应用列表C中的方法。列表D为对应的VB.NET代码。
列表C
public sealed class Singleton2 ...{
private static readonly Singleton2 instance = null;
private static bool flag = false;
private int count = 0;
private Singleton2() ...{ }
public static Singleton2 GetInstance() ...{
if (!flag) ...{
instance = new Singleton2();
flag = true;
}
return instance;
}
public int Count ...{
get ...{ return count++; }
} }
列表D
Public NotInheritable Class Singleton2Class Singleton2
Private Shared _instance As Singleton2 = Nothing
Private Sub New()Sub New()
End Sub
Public Shared Property Instance()Property Instance() As Singleton2
Get
If (_instance Is Nothing) Then
_instance = New Singleton2()
End If
Return _instance
End Get
End Property
Private _count As Integer
Public ReadOnly Property Count()Property Count() As Integer
Get
Return (_count + 1)
End Get
End Property
End Class
只有当(如果)GetInstance方法被调用时,第二个实例才会建立对象。因此,如果从不使用对象,就不会建立对象,这样就可节省系统资源。它应用一个静态标记变量来处理对象。
由于总是只有对象的一个实例,因此第一个方法常用来处理线程问题。在第二个实例中,线程可能会引起问题,导致每个线程出现单独实例。你可以进一步应用锁定的方法来控制创建对象,但在本文我们不讨论这个问题。为了保证线程安全,你应使用第二种方法。
结论
设计模式是一个大家熟悉的概念,它一直为开发社区所试验、测试、调整。单态设计模式是一个在应用中提供单一对象访问点的优秀方法。记得在今后的项目中应用单态模式,你可以找到许多适用单态模式的情形。
0
相关文章
