想对这段代码提出意见:
public class Person
{
public Person(string name, string details)
{
this.Name = name;
this.Details = details;
}
public string Name { get; private set;}
public string Details { get; private set; }
public static List<Person> Instance
{
get
{
if (_person == null)
{
_person = new List<Person>();
}
return _person;
}
}
public static void AddPerson(Person person)
{
if (Instance != null)
{
if (person != null)
{
Instance.Add(person);
}
}
}
private static List<Person> _person;
}
List的单身人士。看到一个单一的Class更常见,只是不确定这是否是一个好的做法?如果这是正常/坏/好的话会有什么意见吗?
答案 0 :(得分:1)
在许多情况下使用Singleton并不是很好,但如果您要使用,请尝试隔离它并尽量不要直接使用
例如: -
public interface IPeopleRepository : IEnumerable<Person>
{
void AddPerson(Person person);
}
public class Repository
{
// Singleton isolated to here...
public static Repository Of { get; } =
new Repository() { People = new PeopleRepsository()};
public IPeopleRepository People { get; private set; }
}
public class PeopleRepsository : IPeopleRepository
{
private List<Person> People { get; set; } = new List<Person>();
public IEnumerator<Person> GetEnumerator()
{
return People.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void AddPerson(Person person)
{
if(person!= null) People.Add(person);
}
}
public class Person
{
public Person(string name, string details)
{
this.Name = name;
this.Details = details;
}
public string Name { get; private set; }
public string Details { get; private set; }
public override string ToString()
{
return $"{Name} : {Details}";
}
}
public class Foo
{
private readonly IPeopleRepository _people;
public Foo(IPeopleRepository people)
{
_people = people;
}
public void Bar()
{
_people.AddPerson(new Person("Foo", "Bar"));
_people.ToList().ForEach(Console.WriteLine);
}
}
class Program
{
static void Main(string[] args)
{
// you can get it here.
Repository.Of.People.AddPerson(new Person("hi", "there"));
// but instead of using it everywhere... inject it where you can
var foo = new Foo(Repository.Of.People);
foo.Bar();
}
}
答案 1 :(得分:0)
Singleton模式是限制创建同一对象的另一个实例。 对当前代码进行小幅调整,强制每个消耗你班级的人使用你的“AddPersons”方法。
只需将构造函数设为私有,这样就无法创建类的新对象。
您的方法语法类似于
public static void AddPerson(string name, string details){...}