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

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

91 件のコメント:

  1. 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.

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

    返信削除
  3. 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

    返信削除
  4. 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

    返信削除
  5. 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.

    返信削除
  6. 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! 일본야동

    返信削除
  7. 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 일본야동

    返信削除
  8. 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. 국산야동

    返信削除
  9. 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!!! 일본야동

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


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

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

    返信削除
  13. 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.
    사설토토놀이터

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

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

    Try to check my webpage :: 출장안마

    返信削除
  16. 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

    返信削除
  17. 카지노 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.

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



    返信削除
  19. 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.

    返信削除
  20. 스포츠마사지 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.

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

    返信削除
  22. 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)

    返信削除
  23. 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!
    경마사이트
    경마

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

    返信削除

  25. 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: 일본경마

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

    返信削除
  27. 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.
    오피월드

    返信削除
  28. 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 -
    오피월드


    返信削除
  29. 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. 토토

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

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

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


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

    返信削除
  34. 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

    返信削除
  35. searching for such an informative post since many days and it seems my search jst ended here.Good work.Keep posting. 온라인카지노

    返信削除
  36. Web medikal yatan hasta ürünlerini uygun fiyatlarla eve teslim etmekteyiz. Evinizde yatan hastanız varsa hasta yatağı kiralama çeşitleri, yatan hastalar için havalı yatak modellerimizde vardır.

    hasta yatağı kiralama

    返信削除
  37. hasta karyolası kiralama


    Medikal Türkiye hasta karyolası satış ve kiralama hizmeti vermektedir. Hasta yatağı imalatı yapmaktayız.

    返信削除
  38. I have read several excellent stuff here. Definitely price bookmarking for revisiting. I surprise how a lot attempt you put to make this sort of magnificent informative Feel free to visit my website; 먹튀검증가이드

    返信削除
  39. magnificent put up, very informative. I'm wondering why the opposite experts of this sector don't notice this. You must continue your writing. I am confident, you have a huge readers' base already! Feel free to visit my website; 배트맨토토프로

    返信削除
  40. 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.메이저놀이터

    返信削除
  41. This type of blog that's brought big impacted to the readers, and thankful to that, click this out too.먹튀검증

    返信削除
  42. All your hard work is much appreciated. This content data gives truly quality and unique information. I’m definitely going to look into it. Really very beneficial tips are provided here and, Thank you so much. Keep up the good works. 사설토토

    返信削除
  43. This content data gives truly quality and unique information. I’m definitely going to look into it. Really very beneficial tips are provided here and, Thank you so much. Keep up the good works. 안전놀이터

    返信削除
  44. I’m definitely going to look into it. Really very beneficial tips are provided here and, Thank you so much. Keep up the good works. 메이저놀이터

    返信削除
  45. Magnificent goods from you, man. I've understand your stuff previous to and you're just extremely great 토토

    返信削除
  46. happy to finally find a post with what I want. casino You have inspired me a lot. If you are satisfied, please visit my website and leave your feedback.Commercial Cleaning Perth

    返信削除
  47. Totally loved your article. Looking forward to see more more from you. Meanwhile feel free to surf through my website while i give your blog a read. 토토

    返信削除
  48. Genuinely when someone doesn’t understand afterward its up to other viewers that they will help, so here it takes place. 카지노사이트

    返信削除
  49. "I've been exploring for a little bit for any high-quality articles or weblog posts on this kind of house .
    Exploring in Yahoo I finally stumbled upon this website.
    Studying this information So I'm glad to show that I have an incredibly just right uncanny feeling I found out exactly what I needed.
    I most indubitably will make sure to do not disregard this site and give it a look on a constant basis."

    야한동영상
    오피헌터
    출장안마
    안마

    返信削除
  50. I like your all post. You have done really good work. T토토

    返信削除
  51. Its an amazing website, really enjoy your articles. Helpful and interesting too. Keep doing this in future. I will support you. 슬롯머신

    返信削除
  52. Many thanks for the article, I have a lot of spray lining knowledge but always learn something new.
    카지노사이트
    토토
    온라인카지노

    返信削除
  53. I really appreciate this post. 온라인카지노 I have been looking all over for this! Thank goodness I found it on Bing. You have made my day! Thanks again!

    返信削除
  54. Great Information sharing .. 스포츠토토 I am very happy to read this article .. thanks for giving us go through info.Fantastic nice. I appreciate this post.

    返信削除
  55. You made some respectable factors there. I seemed on the web for the issue and found most people will go along with together with your website. Feel free to visit my website; 카지노사이트

    返信削除
  56. How to Beat the 메이저놀이터, and How They'll Stop You

    返信削除
  57. Interesting blog this. its quite informative article.
    오피헌터

    返信削除
  58. A very creative and wonderful idea, I think your ideas will be implemented and invent many other ideas. 사설토토

    返信削除
  59. Aw, this was an incredibly good post. Finding the time and actual effort to create a good article… but what can I say… I procrastinate a whole lot and never seem to get nearly anything done. 온라인카지노

    返信削除
  60. I want you to thank for your time of this wonderful read!!! I definately enjoy every little bit of it and I have you bookmarked to check out new stuff of your blog a must read blog! 카지노사이트

    返信削除
  61. Youre so cool! I dont suppose Ive read something such as this before. So nice to find somebody with authentic applying for grants this subject. Feel free to visit my website; 카지노사이트위키

    返信削除
  62. 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. Feel free to visit my website; 카지노사이트링크

    返信削除
  63. This paragraph will assist the internet people for creating new website or even a weblog from start to end. 바카라사이트

    返信削除
  64. Great job for publishing such a beneficial web site. 토토사이트

    返信削除
  65. Thanks for your marvelous posting! I really enjoyed reading it, you could be a great author. I will be sure to bookmark your blog and definitely will come back in the foreseeable future. CLICK IT: 토토

    返信削除
  66. You have written this article with lots of creativity. You have used such impactful words. But here is a small suggestion from my side, you can make it more expressive by using some of the strong content tools. For reference you can read Rahu in the 11th house in Navamsa chart.

    11th house
    birth chart
    Why 222 Is a Powerful Sign

    返信削除
  67. 바카라
    We must be more passionate about everything espeCially when it comes in our nature and environment check this out also >>

    返信削除
  68. wooow excellent nice post...online bookkeeping allows an accountant or a bookkeeper to provide their services to their clients, remotely. Virtual bookkeeping is sometimes called online bookkeeping or read more

    返信削除
  69. very informative and it has helped me a lot And what promotes my business visit our site: Toronto Boat Rentals

    返信削除
  70. the most vital info for me.And i’m glad reading your article. But want to remark on some general things, The web site style is great, the articles is really nice Private Homecare

    返信削除
  71. I will take a note of your site and keep checking for new details about once a week.
    I subscribed to your Feed too. 먹튀검증

    返信削除
  72. Thank you so much sharing this information because I have learning java language. And i have also website for Strengthening Relations "Sambandhah Counseling"

    返信削除
  73. Thanks for sharing an informative blog.It was really nice blog.Keep sharing
    abogados de bancarrota de virginia

    返信削除
  74. thanksyou so much this site blog is very nice and carefull it was really nice blog keep sharing Sticker Labeling Machine

    返信削除
  75. Nice post about java singleton pattern , thank you so much sharing very important information about java. Siddhivinayak Industries are one of the leading Automatic Liquid Filling Machine Manufacturer.

    返信削除
  76. Are you facing difficulties in locating resume maker agency? Do you need resume making servie to prepare your resume for interview? We at Gotoassignmenthelp is committed to providing high-grade services to all students and professionals to get their resume by our resume writing service in Australia. So if looking for resume writing service then hire our Resume Maker in Australia service now.

    返信削除
  77. What is Online Counselling? Online counseling, also known as e-counseling or teletherapy, is a form of mental health counseling provided through digital communication channels, primarily the internet. It involves the use of technology to connect clients with licensed mental health professionals or counselors, allowing individuals to receive therapeutic support and guidance from the comfort of their own homes or any other convenient location. HopeQure is a premium counselling provider agency which offer online counselling in various fields. For getting more information, check our website now.

    返信削除
  78. 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.
    Fatal Accidente de Motocicleta Virginia

    返信削除
  79. motorcycle accident i 95 virginia
    The Java Singleton pattern is a crucial design choice for managing a single instance of a class, ensuring only one object is created. It is particularly useful for resource-intensive objects and simplifies code maintenance and performance. The pattern has been applied in several projects and has proven to be a reliable and efficient solution. This article provides a step-by-step explanation of its implementation, making it accessible for developers at all levels. Understanding Java Singleton is essential for writing efficient, memory-conscious code, and this comprehensive overview of Singleton with clear examples is a must-read for Java developers aiming to write clean and efficient code.

    返信削除

  80. The Java Singleton pattern is a design pattern used to ensure that a class has only one instance and provides a global point of access to that instance. It is achieved by making the class's constructor private and providing a static method to return the single instance. This pattern is useful when you want to control access to a resource or limit the instantiation of a class to a single object. While it can be beneficial for maintaining a single point of control, it should be used judiciously, as it can lead to global state and make testing more challenging.
    mejores abogados de accidentes de camiones

    返信削除
  81. buen abogado para accidente de cocheThe class effectively implements the Singleton pattern, using a private static instance and private constructor to restrict external instantiation. The instance variable is initialized within the class, ensuring a single instance is created during class loading. The private constructor prevents external instantiation, enforcing the Singleton pattern's design principle. The `getInstance` method provides a standardized way to access the Singleton instance, allowing external classes to obtain the single instance. Naming conventions are clear and consistent, enhancing code readability and maintainability. The implementation is thread-safe, as the instance is initialized during class loading. Code documentation with comments explaining the class's purpose and functionality would enhance understanding for developers unfamiliar with the codebase.

    返信削除
  82. This article is increasing the interest to learn more about this topic.es un dui un delito grave en Virginia

    返信削除