再谈单例模式
来源:互联网 发布:java软件开发自学 编辑:程序博客网 时间:2024/06/13 09:19
class1:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Generic;
using System.Text;
namespace WindowsApplication1
{
public abstract class Class1
{
private string owner;
private string name;
private static Class1 _instance = null;
{
public abstract class Class1
{
private string owner;
private string name;
private static Class1 _instance = null;
protected static Class1 Instance
{
get
{
//if (Instance == null)
//Instance = new aaa(location, name);
//return Instance;
return _instance;
}
set
{
_instance = value;
}
}
{
get
{
//if (Instance == null)
//Instance = new aaa(location, name);
//return Instance;
return _instance;
}
set
{
_instance = value;
}
}
//public static Class1 CreateInstance(string location, string name)
//{
// if (Instance == null)
// Instance = new aaa(location, name);
// return Instance;
//}
//{
// if (Instance == null)
// Instance = new aaa(location, name);
// return Instance;
//}
public string Owner
{
get { return owner; }
set { owner = value; }
}
public string Name
{
get{ return this.name; }
set{ this.name = value; }
}
{
get{ return this.name; }
set{ this.name = value; }
}
/// <summary>
///
/// </summary>
/// <param name="owner"></param>
public Class1(string owner)
{
this.owner = owner;
}
///
/// </summary>
/// <param name="owner"></param>
public Class1(string owner)
{
this.owner = owner;
}
public abstract string GetYear();
}
public class aaa : Class1
{
private string location;
{
private string location;
public string Location
{
get { return location; }
set { location = value; }
}
{
get { return location; }
set { location = value; }
}
public static Class1 CreateInstance(string location, string name)
{
if (Instance == null)
Instance = new aaa(location, name);
return Instance;
}
private aaa(string location,string owner):base(owner)
{
this.location = location;
}
{
if (Instance == null)
Instance = new aaa(location, name);
return Instance;
}
private aaa(string location,string owner):base(owner)
{
this.location = location;
}
public override string GetYear()
{
return DateTime.Now.Year.ToString();
}
}
{
return DateTime.Now.Year.ToString();
}
}
}
class2:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Generic;
using System.Text;
namespace WindowsApplication1
{
public abstract class BaseClass
{
public static BaseClass instance = new Subclass();
{
public abstract class BaseClass
{
public static BaseClass instance = new Subclass();
//protected BaseClass() { }
public abstract string GetYear();
}
}
public class Subclass : BaseClass
{
{
public static void main(string[] args)
{
string str = instance.GetYear();
Console.WriteLine(str);
}
{
string str = instance.GetYear();
Console.WriteLine(str);
}
public override string GetYear()
{
return System.DateTime.Now.ToString();
}
{
return System.DateTime.Now.ToString();
}
}
}