2012年12月25日火曜日

Java Singletonパターンってなに?

こんにちは、B13の小林です
まさかのトリです。びっくりしました
今回は、自分の復習も兼ねてSingletonパターンについて書いてみたいと思います。

Singletonパターンって何?

オブジェクト指向プログラミングでのデザインパターンの一つです。
デザインパターンとは、プログラミングをするときによく直面する問題と、
その解決策をテンプレート化したものの集まりです。
要するにプログラミングの先輩たちが
「俺たちがよく見る問題をきれいに解決する方法
に名前を付けたから、参考にしてね!」
っていうやつです。

で、Singletonパターンは「インスタンスを一つしか生成したくない!」という問題を解決する
方法を記したパターンです。

方法を元に作ったプログラムはこちらになります。

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

 private Singleton(){}

 public static Singleton getInstance(){
  return instance;
 }
 //この後に使いたいメソッドやフィールドを追加していく
 }

あらかじめinstanceに自分自身を生成しておき、 getInstance()が呼び出されたときに
それを返します。
コンストラクタとinstanceがprivateなので、 getInstance()を使わないとアクセスできないため、
インスタンスを一つしか生成できない形になっています。

 

Singletonパターンはどう役立つの?

インスタンスを2つ以上生成してもムダが増えるだけの場合や
生成時の初期化に時間にかかる場合、
サーバ等のマルチスレッド環境で同じリソースを扱いたい場合
にSingletonパターンを使ってみるといいと思います
しかし、これは個人製作や小規模のプログラムでは必要ないことも多いです。
newを一回しかしないっていうことを守っておけばいいのですから。
なので、特に役立つ場面は
 「インスタンスを一つしか生成したくない!」ということを
「このプログラムに携わる人に知ってもらいたい時」
だと思います。

使う時に気を付けることは?

一つだけ、僕が実際にやったミスを紹介します。
サーバ構築時に上のプログラムを書き換えて
class Singleton{
 private static Singleton instance = null;

 private Singleton(){//いろいろ結構多め}

 public static Singleton getInstance(){
  if(instance == null){
   instance = new Singleton();
  }
  return instance;
 }
 //いろいろ
 }

と「このクラスを最初に使う場合だけ生成する」と書き換えました。
そうするとマルチスレッドのため、同時にgetInstance()を実行される場合があり、
結果的にインスタンスが2つ以上作られてしまったというのがありました。
そうなるとシングルトンの意味がないので、使う際には気を付けてください

まとめ  

Singletonパターンについて書いていきました。 これにかぎらず、デザインパターンは知っていれば、いざ出くわしたときに
「このクラスはこういうことをさせたいんです!」という作った人の意図をスムーズに理解する
ことができると思います。

以上で終わります
ありがとうございました。

48 件のコメント:

  1. Mohon ijin berpromosi. service Ac segala jenis merk. kami service Ac mencakup wilayah coverage seluruh Surabaya, Gresik, Sidoarjo. kami juga menerima jasa service perbaikan AC bongkar dan pasang AC. pekerjaan kami cepat, tepat, profesional, harga kompetitif di banding harga jasa luaran.
    service ac split sidoarjo
    tukang service ac sidoarjo
    service ac surabaya sidoarjo
    service ac surabaya selatan
    service ac surabaya timur
    service ac surabaya barat
    service ac surabaya utara
    service ac kota surabaya

    SPLIT-TYPE AIR CONDITIONERS
    MULTI-SPLIT AIR CONDITIONERS
    CHILLED WATER FAN COIL UNITS
    VRF AIR CONDITIONERS
    CHILLERS
    WINDOW-TYPE AIR CONDITIONERS

    http://jualjasaacsurabaya.blogspot.com
    Segera hubungi kami, dan kami akan datang kerumah Anda 24 Jam Non Stop.
    (Hari Sabtu / Minggu / Hari Libur buka)
    PIN BBM : 54BE0B4B / 5474CD93 / TELP : 085645475574

    返信削除
  2. Thanks for sharing, nice post!

    Đến với Bruno.vn - shop thoi trang dep o tphcm các bạn tha hồ lựa chọn cho mình những mẫu áo sơ mi nam trắng đẹp hay bạn thắc mắc mua quần short nam giá rẻ hay thắc mắc mua quần jean ở đâu đẹp tphcm thì đến với chúng tôi. Ngoài ra, tại đây có bán thương hiệu thời trang nổi tiếng thế giới với những mẫu áo thun nam đẹp 2015 tha hồ lựa chọn, hay với mẫu áo khoác nam đẹp uy tín, giá rẻ với các kiểu quần jean nam đẹp, đa dạng mẫu mã hay mẫu quần kaki nam đẹp thì đến với Bruno - shop quần jean nam tại tphcm hay địa chỉ shop quần áo nam hàng hiệu cực uy tín. Đến với Bruno.vn là địa chỉ shop áo sơ mi nam tphcm bạn có thể chọn áo thun với shop áo thun nam thời trang hàng hiệu hay shop áo khoác nam cực cá tính với nhiều mẫu áo khoác da nam đẹp hay hướng dẫn bạn phân biệt quần jean levi's thật giả cực hay hay bạn có thể chọn thoi trang h & m cho mình hay bạn có thể chọn quà tặng chồng nhân ngày sinh nhật tại Bruno, hay bạn muốn quà tặng bạn trai ngày sinh nhật thì đến với chúng tôi. Bạn băn khoăn mua áo sơ mi nam ở đâu tại tphcm thì đến Bruno.

    返信削除
  3. Exporthub is an international b2b marketplace catering to thousands of globally active manufacturers & suppliers from all industries with its safest trade services. Media Mistakes

    返信削除
  4. hy
    thanks for sharing this blog

    plz visit 123movies





    返信削除
  5. QuickBooks is one of the most efficient financial management software that can help business owners to complete and maintain the records of daily accounting and financial transactions.
    Transfer Quickbooks data to a new pc

    返信削除
  6. If you found any minor or major issue in Quickbooks software, you can download QB Tool Hub which is the combination of all essential tools in a single application. Rather than download an individual tools, you can use this tool to save your time.
    Download Quickbooks tool hub

    返信削除
  7. Quickbooks connection diagnostic tool is a tremendously astonishing tool. It is capable of rectifying the errors and issues that one might face while opening the Quickbooks company file in a multi-user environment. So, basically, if you Download QuickBooks Connection Diagnostic Tool then you can fix almost all the network-related issues.

    返信削除
  8. I’d really love to be a part of online community where I can get responses from other knowledgeable individuals that share the same interest. If you have any recommendations, please let me know. Appreciate it! 일본야동

    返信削除
  9. I must say you have written a great article. The way you have described everything is phenomenal. If you have time, please visit my site 일본야동

    返信削除
  10. Your article is very informative and helpful to me. Thank you for the post it’s really nice.this is more good! do visit my site here. 국산야동

    返信削除
  11. Hello there! Nice article!!! But anyways here’s one of the trusted online baccarat site we can offer you so many promo and event everyday!! Good luck!!! 일본야동

    返信削除
  12. Nice post. I learn something new and challenging on blogs I stumbleupon on a daily basis. 국산야동


    返信削除
  13. Thank you for providing a good quality 온라인카지노 article.

    返信削除
  14. Nice one! Thank you for sharing this post. 온라인카지노Your blog posts are more interesting and impressive.

    返信削除
  15. I really enjoy your web’s topic. Very creative and friendly for users. Definitely bookmark this and follow 스포츠토토it everyday.

    返信削除
  16. It’s so good and so awesome. I am just amazed. 온라인카지노I hope that you continue to do your work like this in the future also.

    返信削除
  17. This type of article that enlighted me all throughout and thanks for this.This going to be excitement and have fun to read. thank to it. check this out to for further exciting.
    사설토토놀이터

    返信削除
  18. This type of blog that's brought big impacted to the readers, and thankful to that, click this out too.
    파워볼사이트닷컴

    返信削除
  19. You actually explained this terrifically!

    Try to check my webpage :: 출장안마

    返信削除
  20. CuCoTV is your one stop mobile app that helps you stream a wide range of high quality movies and series. It is comparatively a very new app but has all great capabilities of streaming catchup tv shows and entertainment content in 1080p. cucotv

    返信削除
  21. 카지노 Wow, excellent post. I'd like to draft like this too - taking time and real hard work to make a great article. This post has encouraged me to write some posts that I am going to write soon.

    返信削除
  22. 토토 Thanks so very much for taking your time to create this very useful and informative site. I have learned a lot from your site.



    返信削除
  23. 스포츠토토 Amazing! Its really awesome paragraph, I have got much clear idea concerning from this post.

    返信削除
  24. Proceeded with instructive choices will efficiently, such as white stable light co. Great on sign in should get into the worker entrance will give of installments. Multi month following the left portion of the key phrase. As soon as you can permit you need to share your company related to love during the accreditation. Entryway establishment direct you will need to land their standing chances to your 성인야설

    返信削除
  25. I can’t imagine focusing long enough to research; much less write this kind of article 휴게텔. You’ve outdone yourself with this material. This is great content.

    返信削除
  26. 스포츠마사지 I can’t imagine focusing long enough to research; much less write this kind of article. You’ve outdone yourself with this material. This is great content.

    返信削除
  27. Excellent post but I was wanting to know if you could write a little more on this subject? I’d be very grateful if you could elaborate a little bit more 출장마사지. Many thanks!

    返信削除
  28. I will remember to bookmark your blog and will
    eventually come back from now on. 온라인카지노

    返信削除
  29. Very good written article. It will be supportive to anyone who utilizes it, including me. Keep doing what you are doing ? can’r wait to read more posts.
    very nice article. 슬롯머신
    (mm)

    返信削除
  30. I savour, lead to I found exactly what I used to be having a look for. You’ve ended my four day long hunt! God Bless you man. Have a nice day. Bye 메이저사이트

    返信削除
  31. I used to be suggested this blog through my cousin. I’m no longer sure whether this submit is written through him as
    nobody else understand such detailed approximately my trouble.
    You’re wonderful! Thank you!
    경마사이트
    경마

    返信削除
  32. I really enjoyed this blog post, thank you for sharing it. I’ll return for more. See you soon! 바카라

    返信削除
  33. This paragraph will help the internet visitors for building up new web site or even a weblog from start to end. 토토사이트

    返信削除

  34. Hey I'm at work surfing around your blog from my new iphone 3gs! Just wanted to say I
    love reading through your blog and look forward to all your posts! Carry on the superb work!

    Review my page please: 일본경마

    返信削除
  35. Just admiring your work and wondering how you managed this blog so
    well. It’s so remarkable. 룰렛

    返信削除
  36. I have read your blog it is very helpful for me. I want to say thanks to you. I have bookmark your site for future updates.
    오피월드

    返信削除
  37. Are you the one who studies this subject?? I have a headache with this subject. Looking at your writing was very helpful.
    온라인경마

    magosucowep

    返信削除
  38. Hurrah, that's what I was looking for, what a material!

    existing here at this website, thanks admin of this web page.

    Feel free to surf to my webpage -
    오피월드


    返信削除
  39. I want to say that this post is awesome, nice written and include almost all significant infos. I’d like to see more posts like this. 토토

    返信削除
  40. really happy found knew this website it very informative. 바카라사이트인포

    返信削除
  41. I stumbled onto your blog and read a few post.I m very pleased to read this article. 카지노사이트

    返信削除
  42. Found your post interesting to read.but I think your writing is the cleanest I've ever seen. 온라인카지노

    返信削除
  43. 카지노사이트 you are in point of fact a excellent webmaster. The website loading pace is amazing.


    返信削除
  44. 스포츠토토 I believe you have noted some very interesting points, appreciate it for the post.

    返信削除
  45. 토토사이트 I have read a few good stuff here. Definitely value bookmarking for revisiting.

    返信削除
  46. my cousin stole my apple ipad and tested to see if it can survive a 25 foot drop, just so she can be a youtube sensation. organic coffee beans

    返信削除