Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I am writing a game in Monogame framework and well
there are some objects that have only 1 instance
(but that does not necessarily mean that there should be only 1
instance) during the lifespan of an application by default,
like for example ContentManager.
Now what's bugging me is that I am not sure what is a better practice and why:
To make that object public static and access it from other classes
to use that static instance to load stuff
or
Pass that object as an argument to other classes constructor and use it that way
Just to add another option, you can use the singleton pattern to restrict the creation of new classes, like a GameManager. This pattern comes with cons and pros, so you need to analyze your requirements.
public final class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
The simplest way to implement the implement the pattern is to have a class with a private constructor, a static parameter for your instance and a method to return the instance.
https://en.wikipedia.org/wiki/Singleton_pattern
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I want to understand the use of "protected" keyword in the following code (line 3).
public class PlayerData
{
static protected PlayerData instance;
static public PlayerData Instance { get { return instance; } }
public int health;
}
public class GameManager
{
PlayerData.Instance.health = 10;
}
A private field is not accessible from a child class.
A protected field can be.
If the field is protected, we can inherit from this class and use this field instead of the property.
This avoids the use of the getter which is a method, and that is a crazy time consuming via a CPU PROC CALL and RET using the CPU STACK to return the reference.
Thus it is more speed optimized to use the field instance instead of teh property Instance because we directly use the reference without the need of a method call that will slow down the process and the current thread, thus the game.
Approximately ~5x faster, way to speak vaguely, for each usage.
But that said, we must be carefull to not change the underlying object instance, unless we have a good reason. This field could be read-only, but it is not, who knows why. Perhaps to be able to change the object... either it is just an oversight, or this ref is assigned outside a constructor, or can be reassigner at any time.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I was looking for approaches that could be used to access a static class which contains private static methods to unit test.
I came across PrivateObject and PrivateType, I do not understand what the difference between them is, and how you would decided to use either one.
BusinessLogic
public static Class BarLogic(){
private static void FooBar(){
//do something here
}
}
API
public class FooService(){
BarLogic.FooBar();
}
The difference is whether you're accessing otherwise inaccessible instance members or static members.
In the example below, you would use PrivateObject to access _someInstanceField, and PrivateType to access _someStaticField.
public class SomeObjectWithInAccessibleMembers
{
private int _someInstanceField;
private static int _someStaticField;
}
Given that your test was in a separate assembly from this class (and therefore unable to to see its internal members) you could do this:
var privateObject = new PrivateObject(new SomeObjectWithInAccessibleMembers());
privateObject.SetField("_someInstanceField", 1);
Assert.AreEqual(1, privateObject.GetField("_someInstanceField"));
var privateType = new PrivateType(typeof(SomeObjectWithInAccessibleMembers));
privateType.SetStaticField("_someStaticField", 1);
Assert.AreEqual(1, privateType.GetStaticField("_someStaticField"));
I've never used this. I didn't even know about it. My first reaction is that it couples the test to the inner implementation of the class instead of testing its public methods. Then it couples it some more by using strings for member names, so the tests could break just by changing a member name.
On the other hand, I've worked in projects where a) I want to add unit tests, but b) I can't refactor to make it more testable. It's not my first choice but I might have a use for this. Thanks!
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
In the case of the singleton class seen below, what is the proper way to initialize MyList? Do I refer directly to the field MyList (Option 1) or to Instance.MyList (Option 2)? What's best practice here? My gut says go through Instance, but I'm second-guessing myself and cannot find a definitive answer anywhere.
public class Foo
{
private readonly static Lazy<Foo> _instance =
new Lazy<Foo>(() => new Foo());
private List<string> MyList;
public static Foo Instance
{
get { return _instance.Value; }
}
private Foo()
{
MyList = new List<string> {"a","b","c"}; //Option 1
Instance.MyList = new List<string> {"a","b","c"}; //Option 2
}
}
To start with, I would say that either way is fine. That being said, I prefer the option that doesn't use the "Instance" identifier. The concept of the instance really belongs to the code outside of the singleton class. Inside the class, the fact that it is a singleton should be well known. Thus, specifying the Instance identifier is redundant.
The Singleton pattern is for creating types that can only have one instance, but are still treated like instances of a type, rather than being treated as just a type like static types. So if MyList is part of the single instance, then it should be an instance variable on that instance, not a static member of the class.
One of the perks of the Singleton pattern is that it is easier mock for testing and also easier to transition to using multiple instances later, compared to using static members and classes. For these purposes, making MyList an instance member also helps.
If using an instance, you can write MyList or this.MyList within that instance or Instance.MyList from other places. None of these are more correct than any others, it really depends on what you find readable. The important thing is to not mix conventions, which is the worst readability option.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Just being curious.
If I create 2 objects of a particular class, then 2 instances of the instance methods and the instance variables are present in the memory for that particular class?
EDIT: I tried with static and for sure, only one instance of the members were there but not sure with instance variables though.
If I create 2 objects of a particular class, then 2 instances of the instance methods and the instance variables are present in the memory for that particular class?
Instance fields - yes. Instance methods (including property accessors), no. Code (both instance and static) is shared among all instances.
Note that static classes will create an additional type for each generic parameter used, and each of those types will share one set of static variables, so for example:
// for example only, not intended to be a perfect singleton implementation
public class Singleton<T> where t : new()
{
private static T _Instance;
public T Instance()
{
return _Instance ?? (_Instance = new T());
}
}
Singleton<Class1> and Singleton<Class2> will each have a different object in memory for _Instance.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am using System.Net.HttpClient (.Net 4.5) in my MVC4 project. I know that a single instance of HttpClient can be used for all Http requests across the web app. Here is my implementation of the HttpClient singleton which should return the single instance every time.
public sealed class HttpClientInstance: HttpClient
{
// singleton instance
private static readonly HttpClientInstance instance = new HttpClientInstance();
static HttpClientInstance() { }
private HttpClientInstance() : base() {
Timeout = TimeSpan.FromMilliseconds(15000)));
}
/// <summary>
/// Returns the singleton instance of HttpClient
/// </summary>
public static HttpClient Instance
{
get
{
return instance;
}
}
}
Do you see any issues with this?
I know I could possibly use Ninject to inject the dependency in singleton scope but that is besides the point.
There are a few properties that you cannot change after you have made the first request. I think timeout might be one of them, so be aware of that.
You also need to be careful that individual requests don't mess with the DefaultRequestHeaders as that could confuse other requests.
It is always a good idea to try and share HttpClient instances. Creating a singleton is an extreme case of that but with care it should work just fine for you.