public class Singleton {
// Step 1: Declare a private static instance of the Singleton class
private static Singleton s = null;
// Step 2: Make the constructor private to prevent instantiation
private Singleton() {
}
// Step 3: Provide a public static method to get the instance
public static Singleton getIns() {
if (s == null) { // Check if an instance already exists
s = new Singleton(); // Create a new instance if it doesn't
}
return s; // Return the Singleton instance
}
public static void main(String[] args) {
Singleton s1 = Singleton.getIns();
Singleton s2 = Singleton.getIns();
Singleton s3 = new Singleton();
System.out.println(s1 == s2); // Output should be true
}
}
Я ожидал ошибку компиляции для s3, но он компилируется и работает нормально
как мне создать экземпляр Singleton s3, даже если конструктор является частным, проверен в локальной среде и онлайн-компиляторе, он работает [code]public class Singleton {
// Step 1: Declare a private static instance of the Singleton class private static Singleton s = null;
// Step 2: Make the constructor private to prevent instantiation private Singleton() { }
// Step 3: Provide a public static method to get the instance public static Singleton getIns() { if (s == null) { // Check if an instance already exists s = new Singleton(); // Create a new instance if it doesn't } return s; // Return the Singleton instance }
как мне создать экземпляр Singleton s3, даже если конструктор является частным, проверен в локальной среде и онлайн-компиляторе, он работает
public class Singleton {
// Step 1: Declare a private static instance of the Singleton class
private...
Мне интересно, что считается лучшей практикой в C#: частные/защищенные члены с общедоступными методами получения или публичные методы получения с частными/защищенными методами установки?
public int PublicGetPrivateSetter
{
get;
private set;
}...
Я хочу создать вложенный класс, который может быть создан только его внешним классом.
Поэтому я объявляю класс Inner и его конструктор как частные.
class Outer
{
private:
class Inner
{
friend class Outer;
private:
Inner(int a, int b)
{
SomeValue =...