Singleton: Implementazione di un Data Layer

by sandro 5. January 2009 23:43

Solitamente ci viene sempre ricordato come sia importante in un'applicazione dividere nettamente la parte relativa all'interfaccia grafica (Presentation Layer) dalla parte relativa all'accesso ai dati (Data Layer). Questo è sicuramente utile perchè offre la possibilità di scrivere del codice che sia indipendente dalle tecniche di accesso ai dati. Quello che solitamente si fa in questi casi è frapporre un ulteriore livello (Business Layer) il quale si preoccuperà di astrarre completamente i meccanismi di accesso ai dati, fornendo al presentation layer una interfaccia che rimarrà tale anche se dovesse cambiare il meccanismo di accesso ai dati. Vediamo un semplice esempio in figura:

La classe Form1 istanzia un oggetto di tipo BIZ che contiene la logica di recupero delle informazioni che però devono essere restituite in formato di 'ogetto' Employee. L'istanza di BIZ a sua volta crea un oggetto Data Layer che restituisce un dataReader. Con quest'ultimo l'istanza biz scorrerà il dr per poter costruire un'istanza di tipo Employee. A questo punto non rimane che restituire tale istanza al Presentation Layer. Come si vede dalla figura, nel momento in cui cambiasse modalità di accesso al DB, lo strato di business riuscirebbe a nascondere questo cambiamento, continuando a restituire sempre lo stesso oggetto di tipo Employee.

Esistono comunque dei casi in cui, per motivi di spazio e di performance, è utile utilizzare solo i due livelli di Presentation e Data Layer. E' il caso di alcune applicazioni Mobile. Supponiamo però di avere un'applicazione mobile che utilizza diverse finestre Windows Form. Se ognuna di queste Form dovesse accedere al DB dovrebbe inevitabilmente istanziarsi una classe data layer, come in figura:

A questo punto ecco che ci viene utile il Singleton. Invece di permettere ad ogni Form di istanziare il proprio oggetto business, facciamo in modo tale che ciascun oggetto FORM possa utilizzare l'unica istanza di tipo Data, presente nella nostra applcazione. Un Singleton appunto: una classe che permette la creazione di una sola singola istanza:

Qualcuno potrebbe domandarsi perchè non costruire a questo punto una classe statica. Il motivo è che in una classe statica devo necessariamente utilizzare metodi statici e proprietà statiche. Questo limiterebbe la nostra istanza in uno schema estremamaente rigido che non ci servirebbe alla fine più di tanto. Come si fa a costruire una classe singleton? Innanzitutto è necessario fornire un costruttore non pubblico che verrà chiamato all'interno della classe stessa SOLO 1 VOLTA allorchè un oggetto FORM richiederà per la prima volta un'istanza del Singleton.

Dentro la classe Singleton poi inseriremo dei metodi per poter accedere al DB. Tali metodi ovviamente offriranno meno flessibilità rispetto alla presenza di una classe Business, ma daranno una maggiore performance sia dal punto di vista di occupazione di memoria, sia dal punto di vista della veloctà di accesso al DB. Vediamo in figura come nella dichiarazione della classe ci sono varie proprietà relative al DB da utilizzare. Una in particolare però è la proprieta di tipo ContosoDB che viene dichiarata static proprio perchè sarà l'unica istanza dell'applicazione.

Scorrendo poi il codice troviamo il costruttore. Come si riesce a capire dal sorgente, il costruttore inizializza le variabili precedenti tranne la proprietà ContosoDB. Il fulcro poi è rappresentato dal metodo GetInstance nel quale ci si chiede se la precedente proprietà è null. Se si allora è la prima volta che qualcuno chiede una istanza del singleton e invochiamo il costruttore, altrimenti non è la prima volta che viene chiesta l'istanza e restituiamo quindi l'oggetto già creato.

A questo punto siamo in grado di utilizzare la nostra classe singleton all'interno di tutte le finestre Form della nostra applicazione prendendo un'istanza tramite il metodo GetInstance e poi invocare i relativi metodi quali per esempio GetAllItems() dentro il quale si accede al DB tramite i metodi delle classi SQL. Vediamo infine come è possibile sfruttare la classe Singleton dalla Windows Form:

 In conclusione, il pattern Singleton è un'ottima soluzione nelle applicazione Windpws Mobile in cui più soggetti sono interessati ad accedere al DB tramite una classe del livello Data. Ciò farà sicuramente risparmiare memoria e aumentare le performance di accesso.

sv.

Tags: ,

Comments

1/6/2009 12:44:41 AM #

nome prova

ok good artichle!

nome prova Romania | Reply

1/24/2009 11:50:02 AM #

Busby SEO Test

L'informazione è molto buono .. Grazie per aver condiviso ..

Busby SEO Test | Reply

12/5/2009 11:07:11 PM #

car dealerships ct

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.



Regards
Sweern

car dealerships ct United States | Reply

12/8/2009 8:56:12 PM #

lexus dealers in ny

I was looking for crucial information on this subject. The information was important as I am about to launch my own portal. Thanks for providing a missing link in my business.



Regards
Xmaj

lexus dealers in ny United States | Reply

12/11/2009 10:15:36 PM #

wow gold sale

This is the best post on this topic i have ever read.




Regards
Fox

wow gold sale United States | Reply

12/12/2009 5:38:00 PM #

electronic medical record software

I admire what you have done here.



Regards
Fuchs






electronic medical record software United States | Reply

12/17/2009 3:09:29 PM #

divorce laws in washington state

Thank you for another great article. Where else could anyone get that kind of information in such a perfect way of presentation.


Regards
Walker




divorce laws in washington state United States | Reply

12/27/2009 8:24:31 AM #

Michael

You have some honest ideas here. I done a research on the issue and discovered most peoples will agree with your blog.

Michael United States | Reply

12/28/2009 6:05:22 PM #

Monica

Just wanted to say thanks for this.

Monica United States | Reply

12/30/2009 11:45:38 AM #

Cory

Welcome.  This site is packed with information and everything else you need on this.  Enjoy your tour.

Cory United States | Reply

1/23/2010 8:30:22 PM #

size genetics

You gave tremendous positive points there. I did a search on the topic and found most peoples will agree with your blog.

size genetics United States | Reply

3/12/2010 4:02:03 AM #

Nia Dercole

Hi... For some reason strange things are hapenning with your site layout. The edges of the text are running into each other. I all worked fine yesterday. I don't know if it's my end or if you've made a change... Just thought you might want to look at it. Thanks! Nia Dercole

Nia Dercole United States | Reply

3/17/2010 12:48:43 AM #

son moda

hi admin, your blog's pattern is simple and clean and loving it. Your discussions are extraordinary. You should continue this great work. Greets!!!! son moda

son moda | Reply

3/21/2010 2:45:19 PM #

christian internet dating

Great post! I am just starting out in community management/marketing media and trying to learn how to do it well - resources like this article are incredibly helpful. As our company is based in the US, it?s all a bit new to us. The example above is something that I worry about as well, how to show your own genuine enthusiasm and share the fact that your product is useful in that case.

christian internet dating United States | Reply

3/27/2010 1:52:50 PM #

cordless vacs

Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming. Thanks again and good luck!

cordless vacs United States | Reply

3/27/2010 11:41:35 PM #

View Park CA Garage Door Openers

There are certainly a lot of details like that to take into consideration. That is a great point to bring up. I offer the thoughts above as general inspiration but clearly there are questions like the one you bring up where the most important thing will be working in honest good faith. I don?t know if best practices have emerged around things like that, but I am sure that your job is clearly identified as a fair game.

View Park CA Garage Door Openers United States | Reply

3/29/2010 11:20:11 PM #

Age Of Conan Gold

I have recently started using the blogengine.net and I having some problems here? in your blog you stated that we need to enable write permissions on the App_Data folder...unfortunately I don't understand how to enable it.

Age Of Conan Gold United States | Reply

4/2/2010 10:14:27 AM #

moissanite engagement rings

Completely off topic, but I was looking around.  What are your thoughts on using Facebook and Twitter with your blog?  Have you found them to show much benefit in driving traffic to the site?

moissanite engagement rings | Reply

4/5/2010 5:24:28 AM #

cheats & hints

Oh.. this is strange that my comment isnt shown. Anyway I am willing to say that it's nice to know that someone else also told this as I had trouble locating the same info elsewhere. By the way, fascinating article. Much of the visitors don't think that every blogs must have comments part. On the other hand I conceive that reader comments characterize a blog. So thanks for accepting us discussing on this established webpage. Sincerely yours.

cheats & hints United States | Reply

4/5/2010 11:28:38 PM #

Home Care Seattle WA

That is some inspirational stuff. Never knew that opinions could be this varied. Thanks for all the enthusiasm to offer such helpful information here.

Home Care Seattle WA United States | Reply

4/6/2010 4:48:42 AM #

free mp3 download

All you have to do is set up a base standard Ext.data. ...  to the Ext.Ajax singleton (being a singleton used by all remote connections, ... essere un vantaggio (forse perché Spring è un' implementazione di IoC, ...  2. definizione di un setter protected per l' iniezione in fase di test, e reperimento pull a regime

free mp3 download United States | Reply

4/7/2010 8:24:21 AM #

Cierra Champy

You have to express more your opinion to attract more readers, because just a video or plain text without any personal approach is not that valuable. But it is just form my point of view

Cierra Champy United States | Reply

4/8/2010 4:50:25 AM #

Chase CD Rates

When I originally commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added I get four emails with the same comment.
Is there any way you can remove me from that service?
Thanks!

Chase CD Rates United States | Reply

4/8/2010 6:03:16 AM #

backlinks

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

backlinks United States | Reply

4/8/2010 7:34:03 AM #

stock loan

When I originally commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added I get four emails with the same comment.
Is there any way you can remove me from that service?
Thanks!

stock loan United States | Reply

4/8/2010 11:12:08 PM #

Tianna Dupler

I was very pleased to find this site.I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post.

Tianna Dupler People's Republic of China | Reply

4/9/2010 9:04:35 PM #

Olympia Levanger

I was thinking of using BlogEngine but then I saw that most of the sites I looked either had comments full of spam or they had simply closed the comments altogether. I hope that you have been able to combat the spam because at the moment it is something that is making me stay away from BE.

Olympia Levanger People's Republic of China | Reply

4/10/2010 8:06:59 AM #

Outdoor Patio Fireplace

You got a really useful blog I have been here reading for about an hour. I am a newbie and your success is very much an inspiration for me.

Outdoor Patio Fireplace United States | Reply

4/10/2010 11:51:44 AM #

promotional products

Have you ever considered adding more videos to your blog posts to keep the readers more entertained? I mean I just read through the entire article of yours and it was quite good but since I'm more of a visual learner,I found that to be more helpful well let me know how it turns out! I love what you guys are always up too. Such clever work and reporting! Keep up the great works guys I've added you guys to my blogroll. This is a great article thanks for sharing this informative information.. I will visit your blog regularly for some latest post.

promotional products United States | Reply

4/11/2010 10:13:14 PM #

Home improvement tips

I admit, I have not been on this webpage in a long time... however it was another joy to see It is such an important topic and ignored by so many, even professionals. I thank you to help making people more aware of possible issues.
Great stuff as usual...

Home improvement tips United States | Reply

4/12/2010 1:40:29 AM #

get divorced online in Texas

I came across your site because I was looking for a good site design to emulate - I really like the way your website is laid out.

get divorced online in Texas United States | Reply

4/14/2010 6:22:59 AM #

Dentist Tacoma

I personally have embraced the new technologies and the CMS platforms, I think the new tools only make the web designs better. I am glad that new technologies are coming out in web design that make things easier, improved, and better looking for design.

Dentist Tacoma United States | Reply

4/14/2010 8:24:54 AM #

Interpersonal Relationship Skills

I completely agree with the above comment, the internet is with a doubt growing into the most important medium of communication across the globe and its due to sites like this that ideas are spreading so quickly.

Interpersonal Relationship Skills United States | Reply

4/14/2010 10:57:37 AM #

business cards

Howdy, i read your blog occasionally and i own a similar one and i was just wondering if you get a lot of spam comments? If so how do you prevent it, any plugin or anything you can advise? I get so much lately it's driving me mad so any assistance is very much appreciated.

business cards United States | Reply

4/17/2010 6:07:14 PM #

Kecia Bilich

Stumbled into this site by chance but I’m sure glad I clicked on that link. You definitely answered all the questions I’ve been dying to answer for some time now.  Will definitely come back for more of this. Thank you so much

Kecia Bilich United States | Reply

4/18/2010 9:34:44 AM #

laptops under 300

Good luck getting people behind this one.  Though you make some VERY fascinating points, youre going to have to do more than bring up a few things that may be different than what weve already heard.  What are trying to say here?  What do you want us to think?  It seems like you cant really get behind a unique thought.  Anyway, thats just my opinion.

laptops under 300 United States | Reply

4/19/2010 5:19:55 PM #

pink laundry basket

c

pink laundry basket United States | Reply

4/19/2010 8:26:15 PM #

moving to spain

Your thoughts are amazing. Your blog, not so much.  I dont want to disrespect you, just hear me out.  Add a little something here.  What youre saying is so important itd be a shame if people missed it because they were bored to death.  May be a video or a link to something as powerful as the subject.  Just a suggestion.

moving to spain United States | Reply

4/21/2010 9:45:07 PM #

white bed sheets

c

white bed sheets People's Republic of China | Reply

4/22/2010 10:51:57 AM #

Merchant Account Loan

If I might --perhaps you should consider adding a few images.  I dont mean to disrespect what youve said; its very enlightening, indeed.  However, I think would respond to it more positively if they could be something tangible to your ideas.  Keep it up, but put a little more into it next time.

Merchant Account Loan United States | Reply

4/22/2010 11:22:36 AM #

Dillon Castin

This is one technology that I would love to be able to use for myself. It’s definitely a cut above the rest and I can’t wait until my provider has it. Your insight was what I needed. Thanks

Dillon Castin United States | Reply

4/23/2010 9:44:24 AM #

Hifonics Amps

My husband and I have been looking for this info.  Wondering if you will be posting more about this in the future - will bookmark and come back

Hifonics Amps United States | Reply

4/23/2010 1:42:54 PM #

bathroom accessory sets

What I wouldnt give to have a debate with you about this.  You just say so many things that come from nowhere that Im pretty sure Id have a fair shot.  Your blog is great visually, I mean people wont be bored.  But others who can see past the videos and the layout wont be so impressed with your generic understanding of this topic.

bathroom accessory sets United States | Reply

4/24/2010 3:14:47 AM #

cheap exercise equipment

I hate to sound like a nitpick, but your grammar is just...deplorable.  I want to be interested in this, I really do.  But it seems you spent so much time on the design (which, I will say, is amazing) that you forgot that people actually have to read your blog.  Clean this up...PLEASE.  It could be so much bigger if you just did some work.

cheap exercise equipment United States | Reply

4/24/2010 8:08:36 PM #

Mathew Finan

We take the opportunity of this blog post to inform the net citizens about our effort to create a steady and fair environment for Facebook users. As you may already know Facebook Accounts are SUSPENDED with geometrical progress. We started a petition against this policy and we ask to unite your voice with ours to create the proper attention and rectify this issue with Facebook administration. Current editors at various magazines want to see that there is a certain interest before they create articles to their websites and/or magazines. To all readers and to blog owner we ask to support our petition here : http://FacebookDisabled.me (redirects to petitionspot) - Twitter : http://twitter.com/facebookpetitio . Thank you !!

Mathew Finan United States | Reply

4/25/2010 1:38:25 AM #

multifunction laser printers

Thank you for this blog.  Thats all I can say.  You most definitely have made this blog into something thats eye opening and important.  You clearly know so much about the subject, youve covered so many bases.  Great stuff from this part of the internet.  Again, thank you for this blog.

multifunction laser printers United States | Reply

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
Click to change captcha
  • Comment
  • Preview
Loading



Sandro Vecchiarelli

MeLaureato in Scienze dell'informazione a Pisa, si è occupato di analisi e progettazione software per istituti bancari e pubbliche amministrazioni, approfondendo inoltre gli aspetti della programmazione ad oggetti sin dai primi esordi del web in Italia. Certificato MCSE e MCT si occupa anche di elementi legati al networking e alla sicurezza. Svolge un' importante attività di docenza su argomenti riguardanti la piattaforma .NET, XML e Web services. E' autore di 2 corsi di successo: "Windows Server Security"(MIE1311), riguardante gli aspetti legati alla sicurezza della piattaforma Windows Server, e "Ingegneria del software: tecniche per la costruzione di software di qualità" (MIEAU36) dove vengono affrontate le tecniche per scrivere codice il più possibile robusto, riusabile e performante. Negli ultimi anni ha acquisito anche importanti competenze riguardanti prodotti molto complessi quali Microsoft Biztalk Server, oltre ad aver affrontato l'analisi e lo sviluppo di applicazioni in ambienti embedded quali Windows CE e Pocket PC. Nel 2008 è stato nominato MVP Microsoft Windows Mobile, riconfermato nel 2009 e 2010.

Tag cloud

Page List