簡體   English   中英

如何避免在Java中創建對象?

[英]How to avoid the creation of object in Java?

我是java編程的新手,我有一個類,對於這個類,我創建了兩個對象(obj1,obj2).i不想創建除這些對象之外的其他對象,如果有任何體想要為這個類創建另外一個對象應該只引用第一個或第二個對象(而不是再創建一個對象)。如何做到這一點?請參考下面的代碼

class B 
{ 
 void mymethod()
     {  
       System.out.println("B class method");
          } 
 }   
class Myclass extends B
{ 
 public static void main(String s[])
     {  
       B  obj1=new B();//this is obj1
       B  obj2=new B();//this is obj1
       B  obj3=new B();//don't allow to create this and refer this to obj1 or obj2
          } 
 }

謝謝azam

查看Singleton設計模式。

你需要的是Singleton設計模式。

Class B看起來應該是這樣的:

class B
{
    private static B instance = null;

    private B()
    {
         //Do any other initialization here
    }

    public static B getInstance()
    {
        if (instance == null)
        {
            instance = new B();
        }
        return instance;
    }
}

然后,在你的Myclass ,只需這樣做:

B obj1 = B.getInstance();
B obj2 = B.getInstance();

注意:這不是線程安全的。 如果您正在尋找線程安全解決方案,請參閱Wiki頁面。

編輯:你也可以有一個靜態初始化程序

class B
{
    private static B instance = null;
    static
    {
         instance = new B();
    }


    private B()
    {
         //Do any other initialization here
    }

    public static B getInstance()
    {       
        return instance;
    }
}

從Java 6開始,您可以使用單元素枚舉類型的單例。 根據約書亞布洛赫的有效Java ”一書,這種方式目前是在Java 1.6或更高版本中實現單例的最佳方式

package mypackage;
public enum MyEnumSingleton {
INSTANCE;

  // other useful methods here
}

"This approach is functionally equivalent to the public field approach,
 except that it is more concise, provides the serialization machinery for free, 
 and provides an ironclad guarantee against multiple instantiation, even in the 
 face of sophisticated serialization or reflection attacks. While this approach 
 has yet to be widely adopted, a single-element enum type is
 the best way to implement a singleton."

在Java 1.6之前,應該是單例的類可以像下面這樣定義。

public class Singleton {
private static Singleton uniqInstance;

private Singleton() {
}

public static synchronized Singleton getInstance() {
    if (uniqInstance == null) {
        uniqInstance = new Singleton();
    }
    return uniqInstance;
  }
  // other useful methods here
}

是的單身似乎正確的方式考慮你在這里提供的信息。

默認的單例實現如下:

public class Singleton {
     //holds single instance reference
     private static Singleton instance = null;

     //private constructor to avoid clients to call new on it
     private Singleton()
     {}

     public static Singleton getInstance() 
     {
        if(null == instance)
        {
           instance = new Singleton();
        }

        return instance;
     }
}

現在,您可以通過調用獲取對象的單個實例:Singleton instance = Singleton.getInstance();

請記住,如果您使用線程環境,默認情況下單例不是線程安全的。

您應該使getInstance方法同步以避免意外返回。

public synchronized static Singleton getInstance() 
{
            if(null == instance)
            {
               instance = new Singleton();
            }

            return instance;
}

干杯

一般來說,你需要一個單身模式。 您需要使構造函數成為私有方法。 然后創建一個實例化B類的方法,因此B類只能通過此方法實例化。 看看單身人士模式。 這就是你想要我相信的東西。

你可以使用Singleton。 你有2種可能性。
1。 延遲創建 (這里在調用函數getInstance()創建實例,並檢查實例是否已存在):

class B {
    static private B instance;

    private void mymethod() {
        System.out.println("B class method");
    }

    static public B getInstance() {
        if (instance == null) {
            instance = new B();
        }
        return instance;
    }
}

class Myclass extends B {
    public static void main(String s[]) {
        B obj1 = B.getInstance(); // this is obj1
        B obj2 = B.getInstance();


    }
}

2。 渴望創建 (這里您在第一次調用Class時創建實例):

class B {
    static private B instance = new B();

    private void mymethod() {
        System.out.println("B class method");
    }

    static public B getInstance() {
        return instance;
    }
}

class Myclass extends B {
    public static void main(String s[]) {
        B obj1 = B.getInstance(); // this is obj1
        B obj2 = B.getInstance();

    }
}

創建單例類,就像

public Class A {
    private static Class a = new A();

    public A getA() {
        return a;
    }
}

A類的對象已經在A類中創建。 您無需在外部創建它。 只需使用getA()方法來解除A類的對象。 喜歡 :

A  objA = A.getA();

這叫做Singlton Pattern。

請注意,使用單例是對代碼的一個很大的限制。 當不可能實例多個對象時,它會非常煩人。

特別是當你沒有訪問源....

多線程應用程序的有效方法,以下邏輯可能會有所幫助

public class Singleton {
    private static volatile Singleton _instance;
    private Singleton(){}
    public static Singleton getInstance() {
        if (_instance == null) {
            synchronized (Singleton.class) {
                if (_instance == null)
                    _instance = new Singleton();
            }
        }
        return _instance;
    }
}

我想人們還沒有理解問題陳述。 它說,應創建不超過2個對象。 Singleton創建單個對象並阻止任何進一步的實例化。

  1. 在ur對象類中維護一個靜態變量,在創建對象時將對象的上限增加1
  2. 當需要創建object> bounds時,選擇范圍[1,bound]中的隨機數並返回該對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM