如何在Activity中实现Singleton Pattern

时间:2011-12-21 09:47:02

标签: android

我想在Android中实现Singleton Pattern以重用我的类。谁能给我一个想法? 这是我设定课程的代码。我想使用这个单词

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;

public class Setting extends Activity {
    CheckBox ON;
    private static Setting instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ON=(CheckBox)findViewById(R.id.SoundCheckbox);
        ON.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(ON.isChecked())
                    ON.toggle();
                }
            });
        }

    private Setting() {
        setContentView(R.layout.settings);
    }

    public static synchronized Setting getsetting() {
         if (instance == null) {
             instance = new Setting();
         }
         return instance;
    }

    public Object clone()throws CloneNotSupportedException  {
        throw new CloneNotSupportedException();
    }
}

并在另一个使用此类别时调用此类

Setting settings=new Setting();
Setting settingsobj=Setting.getsetting();

谢谢和注意
RizN81

0 个答案:

没有答案