创建型模式之单件模式

C#相关内容转载
先看这段vb.net代码:
ExpandedBlockStart.gifContractedBlock.gifPublic Class ForComClass ForCom
InBlock.gif    
Public Shared com_counter As Integer
InBlock.gif    
Private Shared glbCom As ForCom
InBlock.gif    
Private legalInst As Boolean
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Private Sub New()Sub New()
InBlock.gif        glbCom 
= Me
InBlock.gif        com_counter 
= com_counter + 1
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Public Shared Function getCom()Function getCom() As ForCom
InBlock.gif        glbCom 
= New ForCom
InBlock.gif        
Return glbCom   '这里用getCom = glbCom也是可以的!
ExpandedSubBlockEnd.gif
    End Function

ExpandedBlockEnd.gif
End Class

com_counter   用来记录创建的实例的个数。

客户端应用:
ExpandedBlockStart.gifContractedBlock.gifPublic Class Form1Class Form1
InBlock.gif    
Inherits System.Windows.Forms.Form
InBlock.gif    
'Inherits Aegis.Libs.Navigator.frmBasePlug
InBlock.gif

ExpandedSubBlockStart.gifContractedSubBlock.gif
Windows Form Designer generated code#Region " Windows Form Designer generated code "
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Public Sub New()Sub New()
InBlock.gif        
MyBase.New()
InBlock.gif
InBlock.gif        
'This call is required by the Windows Form Designer.
InBlock.gif
        InitializeComponent()
InBlock.gif
InBlock.gif        
'Add any initialization after the InitializeComponent() call
InBlock.gif

ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'Form overrides dispose to clean up the component list.
ExpandedSubBlockStart.gifContractedSubBlock.gif
    Protected Overloads Overrides Sub Dispose()Sub Dispose(ByVal disposing As Boolean)
InBlock.gif        
If disposing Then
InBlock.gif            
If Not (components Is NothingThen
InBlock.gif                components.Dispose()
InBlock.gif            
End If
InBlock.gif        
End If
InBlock.gif        
MyBase.Dispose(disposing)
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
InBlock.gif    
'Required by the Windows Form Designer
InBlock.gif
    Private components As System.ComponentModel.IContainer
InBlock.gif
InBlock.gif    
'NOTE: The following procedure is required by the Windows Form Designer
InBlock.gif
    'It can be modified using the Windows Form Designer.  
InBlock.gif
    'Do not modify it using the code editor.
InBlock.gif
    Friend WithEvents Button1 As System.Windows.Forms.Button
InBlock.gif    
Friend WithEvents Button2 As System.Windows.Forms.Button
ExpandedSubBlockStart.gifContractedSubBlock.gif    
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()Sub InitializeComponent()
InBlock.gif        
Me.Button1 = New System.Windows.Forms.Button
InBlock.gif        
Me.Button2 = New System.Windows.Forms.Button
InBlock.gif        
Me.SuspendLayout()
InBlock.gif        
'
InBlock.gif
        'Button1
InBlock.gif
        '
InBlock.gif
        Me.Button1.Location = New System.Drawing.Point(28888)
InBlock.gif        
Me.Button1.Name = "Button1"
InBlock.gif
        Me.Button1.TabIndex = 0
InBlock.gif        
Me.Button1.Text = "Button1"
InBlock.gif
        '
InBlock.gif
        'Button2
InBlock.gif
        '
InBlock.gif
        Me.Button2.Location = New System.Drawing.Point(408256)
InBlock.gif        
Me.Button2.Name = "Button2"
InBlock.gif
        Me.Button2.TabIndex = 1
InBlock.gif        
Me.Button2.Text = "Button2"
InBlock.gif
        '
InBlock.gif
        'Form1
InBlock.gif
        '
InBlock.gif
        Me.AutoScaleBaseSize = New System.Drawing.Size(513)
InBlock.gif        
Me.ClientSize = New System.Drawing.Size(576382)
InBlock.gif        
Me.Controls.Add(Me.Button2)
InBlock.gif        
Me.Controls.Add(Me.Button1)
InBlock.gif        
Me.Name = "Form1"
InBlock.gif
        Me.Text = "Form1"
InBlock.gif
        Me.ResumeLayout(False)
InBlock.gif
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
ExpandedSubBlockEnd.gif
#End Region

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Private Sub Button1_Click()Sub Button1_Click(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles Button1.Click
InBlock.gif        ForCom.getCom()
ExpandedSubBlockEnd.gif    
End Sub

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
Private Sub Button2_Click()Sub Button2_Click(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles Button2.Click
InBlock.gif        
MsgBox(ForCom.com_counter.ToString())
ExpandedSubBlockEnd.gif    
End Sub

ExpandedBlockEnd.gif
End Class

None.gif


如果要控制实例被创建的个数,比如要求只能建立3个该类的实例,就很简单了,把New()方法修改一下,像这样:
ExpandedBlockStart.gifContractedBlock.gif    Private Sub New()Sub New()
InBlock.gif        
If com_counter < 3 Then
InBlock.gif            glbCom 
= Me
InBlock.gif            com_counter 
= com_counter + 1
InBlock.gif        
Else
InBlock.gif            
Throw New Exception
InBlock.gif        
End If
ExpandedBlockEnd.gif    
End Sub

本文标题所指“单件模式”,条件改为 com_counter < 1 就可以了!


用C#:
None.gifusing System;
None.gif
None.gif
namespace WindowsApplication7
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// Summary description for Class1.
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public class ForCom
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
public static Int32 com_counter = 0;
InBlock.gif        
private static ForCom glbCom;
InBlock.gif        
private bool legalInst;
InBlock.gif
InBlock.gif        
private ForCom()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (com_counter < 1)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                glbCom 
= this;
InBlock.gif                com_counter 
= com_counter + 1;
InBlock.gif                legalInst 
= true;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                legalInst 
= false;
InBlock.gif                
throw new Exception();
ExpandedSubBlockEnd.gif            }
            
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public static ForCom getCom()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            glbCom 
= new ForCom();
InBlock.gif            
return glbCom;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gifusing System;
None.gif
using System.Drawing;
None.gif
using System.Collections;
None.gif
using System.ComponentModel;
None.gif
using System.Windows.Forms;
None.gif
using System.Data;
None.gif
None.gif
namespace WindowsApplication7
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// Summary description for Form1.
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public class Form1 : System.Windows.Forms.Form
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
private System.Windows.Forms.Button button1;
InBlock.gif        
private System.Windows.Forms.Button button2;
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Required designer variable.
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        private System.ComponentModel.Container components = null;
InBlock.gif
InBlock.gif        
public Form1()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
//
InBlock.gif            
// Required for Windows Form Designer support
InBlock.gif            
//
InBlock.gif
            InitializeComponent();
InBlock.gif
InBlock.gif            
//
InBlock.gif            
// TODO: Add any constructor code after InitializeComponent call
InBlock.gif            
//
ExpandedSubBlockEnd.gif
        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Clean up any resources being used.
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        protected override void Dispose( bool disposing )
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if( disposing )
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (components != null
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    components.Dispose();
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
base.Dispose( disposing );
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Windows Form Designer generated code#region Windows Form Designer generated code
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Required method for Designer support - do not modify
InBlock.gif        
/// the contents of this method with the code editor.
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        private void InitializeComponent()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
this.button1 = new System.Windows.Forms.Button();
InBlock.gif            
this.button2 = new System.Windows.Forms.Button();
InBlock.gif            
this.SuspendLayout();
InBlock.gif            
// 
InBlock.gif            
// button1
InBlock.gif            
// 
InBlock.gif
            this.button1.Location = new System.Drawing.Point(20872);
InBlock.gif            
this.button1.Name = "button1";
InBlock.gif            
this.button1.TabIndex = 0;
InBlock.gif            
this.button1.Text = "button1";
InBlock.gif            
this.button1.Click += new System.EventHandler(this.button1_Click);
InBlock.gif            
// 
InBlock.gif            
// button2
InBlock.gif            
// 
InBlock.gif
            this.button2.Location = new System.Drawing.Point(304200);
InBlock.gif            
this.button2.Name = "button2";
InBlock.gif            
this.button2.TabIndex = 1;
InBlock.gif            
this.button2.Text = "button2";
InBlock.gif            
this.button2.Click += new System.EventHandler(this.button2_Click);
InBlock.gif            
// 
InBlock.gif            
// Form1
InBlock.gif            
// 
InBlock.gif
            this.AutoScaleBaseSize = new System.Drawing.Size(513);
InBlock.gif            
this.ClientSize = new System.Drawing.Size(456334);
InBlock.gif            
this.Controls.Add(this.button2);
InBlock.gif            
this.Controls.Add(this.button1);
InBlock.gif            
this.Name = "Form1";
InBlock.gif            
this.Text = "Form1";
InBlock.gif            
this.ResumeLayout(false);
InBlock.gif
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// The main entry point for the application.
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        [STAThread]
InBlock.gif        
static void Main() 
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Application.Run(
new Form1());
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void button1_Click(object sender, System.EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            ForCom.getCom();
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void button2_Click(object sender, System.EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            System.Windows.Forms.MessageBox.Show(ForCom.com_counter.ToString());
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif


关于Shared和static的用法:
None.gifC# 所有的程式碼都要存放在 Class,VB.NET 持續支援標準模組。定義在標準模組的函數和變數會在 assembly 中以 global 的方式呈現。標準模組是與 CLS 相容的,C# 無法定義這一點。
None.gif
None.gifC# 和 VB.NET 都在 Class 支援靜態方法、屬性和 fields(在 VB.NET 稱為 Shared)。它們在使用時不需真正建立物件,例如
None.gif
None.gif
class AClass
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif
InBlock.gif    
public static void StaticMethod()
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
InBlock.gif        Console.WriteLine(
"不需要建立物件就可以呼叫");
InBlock.gif
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedBlockEnd.gif}

None.gif
None.gif則呼叫 StaticMethod 只需要
None.gif
None.gifAClass.StaticMethod();
None.gif
None.gif在 C# 呼叫靜態方法只能透過 type 名稱,在 VB.NET 則同時可以利用 type 名稱或是物件的 instance 來呼叫,範例如下
None.gif
None.gifClass AClass
None.gif
None.gif    Public Shared Sub ShareMethod()
None.gif
None.gif        Console.WriteLine(
"可以不建立物件來呼叫函數")
None.gif
None.gif    End Sub
None.gif
None.gifEnd Class
None.gif
None.gif可以透過以下兩種的程式碼使用
None.gif
None.gifAClass.ShareMethod()
None.gif
None.gifDim a As New AClass()
None.gif
None.gifa.ShareMethod()
None.gif
None.gif這變成是哲理性的考量了,C# 提供了紀律:如果你想要建立與物件無關但以函數組成的函式庫(library),你必須建立 Class 來實際地將函數群組在一起,雖然你從來都不會為該 type 建立物件。由於所有的靜態成員仍需以 type 名稱來存取,會強制要求程式設計師明確知道該成員的共享特色。
None.gif
None.gifVB.NET 提供了開發人員更大的彈性。你可以為一般功能函數建立傳統的標準模組,它可以在不指定任何 
class 或模組名稱下直接使用。你可以存取物件的 instance 的 shared 成員,但這有讓 shared 物件與 instance 物件混淆的危險。
None.gif

转载于:https://www.cnblogs.com/silva/archive/2005/08/09/210625.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值