Prototype Design Pattern

এই প্যাটার্ন নিয়ে ভয়ের কোন কারণ নাই। মজার ব্যাপার হল আমি, আপনি না জেনেই এই প্যাটার্ন ব্যবহার করে থাকি। অবাক হচ্ছেন! কিভাবে?

আচ্ছা swift এ structure কি type? reference  না value type? struct হল value type আর class হল reference type।

নিচের code snippet এ Student type এর একটা structure আছে।
আমি প্রথমে student1 বানালাম যার roll = 1, name = AbuBakr, department = CSE
এটার জন্য যে constructor দরকার তার argument এর সংখ্যা 5.

এখন আমার 2nd student2 হাজির হয়ে গেছে, তো তাকেও construct করতে হবে। আবার constructor call দেয়া যায় কিন্তু এত বড় constructor লেখা যেমন ঝামেলা, দেখতে দৃষ্টিকটু-তো বটেই।

তাই student2 তে student1 কপি করলেই সমাধান। এখানে student1 হল prototype, তাই নতুন instance student2 এর সব property value update/clone হয়ে গেছে prototype(student1) থেকে।


ঠিক এই student copy করার কাজটা এবার class এর ক্ষেত্রে apply করবো। ফলাফল ভয়ংকর!!!! student2 update করলে student1 ও update হয়ে যাচ্ছে.


সমস্যাটা কি আসলে? student2 এখানে student1 এর reference কেই point করে আছে। তাই student2 এর value update করলে student1 update হয়ে যাচ্ছে।

সমাধান????

খুব সহজ। student2 তে student1 assign করার সময় জোরপূর্বক একটা নতুন reference তৈরি করে তার মধ্যে property value গুলা copy করে দিলেই ব্যাস।

Comments

Popular posts from this blog

PopIt Serially support page

10405 - Longest Common Subsequence (UVA)