使用构造函数如何做到这一点 [英] Using constructor how to do this one

查看:71
本文介绍了使用构造函数如何做到这一点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用构造函数限制类创建对象



我尝试过:



如何使用构造函数限制类创建对象

how to restrict the class from creating object using constructor

What I have tried:

how to restrict the class from creating object using constructor

推荐答案

将构造函数设为私有:

Make the constructor private:
public class MyClass
   {
   private static MyClass theInstance = new MyClass();
   private MyClass() {}
   public static MyClass GetInstance()
      {
      return theInstance;
      }
   }

该应用只能创建该类的单个实例,因为构造函数仅在类本身内可用。



这也称为单例模式。

The app can only create a single instance of the class, because the constructor is only available within the class itself.

This is also known as a Singleton pattern.


这篇关于使用构造函数如何做到这一点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆