কাদের জন্যঃ Object-oriented programming language সম্পর্কে ধারণা আছে এমন মানুষ।
যা প্রয়োজনঃclass,inheritance,composition,JavaScript সম্পর্কে পূর্ব ধারণা।
Singleton:এটি Creational Design Pattern দলের। এক্ষেত্রে একটি ক্লাসের কেবল একটি instance তৈরি করা হয়। উদাহরণে Person এর constructor এ শর্ত জুড়ে দেয়া আছে যে একের বেশি instance তৈরি করলে বার্তা দেখাবে যে এই class এর কেবল একটি instance সম্ভব। তারপরও কেউ যদি instance/object তৈরি করতে চায় তবে comment out(/*…*/ উঠিয়ে দেই) করে এবং throw কে comment এর মধ্যে ফেলে অগ্রসর হতে পারে। তবে সেক্ষেেত্রেও নতুন instance একই object কে নির্দেশ করবে। উদাহরণে p ও q একই object কে বোঝাচ্ছে।Strict equality operator(===) এক্ষেত্রে true নির্দেশ করছে যা বলছে দু'জনে একই objectকে refer করছে।আর যদি আমরা comment out না করে current set up থাকি তবে দ্বিতীয় instance (q) তৈরির সময় আমাদেরকে অপারগতার বার্তা দেখাবে। এখানে দু'টি private field রয়েছে(s ও obj) , এর মাঝে obj আবার static যাকে Class Person এর মাধ্যমে access করতে হবে।
উদাহরণ:
class Person{
#s="Hi
";
static #obj=null;
constructor(){
if (Person.#obj){
throw document.write("Only one instance can be created!
");
/*
return Person.#obj;
*/
}
Person.#obj=this;
}
getS(){ return this.#s;}
show (){
document.write(this.getS());
}
}
var p=new Person();
p.show();
var q=new Person();
q.show();
/*
document. write(p===q);
if(p===q){
document. write("
Since p and q have pointed to the same object,singleton class Person works!");
}
else{
document. write("
p and q are not same as they pointed to different objects!");
}
*/
কৃতজ্ঞতাঃ এই লেখা তৈরি করতে দরকারি তথ্য নেয়া হয়েছে Wikipedia,www.stackoverflow.com,আকর বই "'Design Patterns:Elements Of Reusable Object-Oriented Software' by Eric Gamma,Richard Helm,Ralph Johnson and John Vlissides(Addisson-Wesley.1994)" ও https://stackoverflow.com/questions/1479319/simplest-cleanest-way-to-implement-a-singleton-in-javascriptএ ব্যবহৃত program থেকে।
মন্তব্য ও যোগাযোগঃ mrh4478@gmail.com
No comments:
Post a Comment