Tanımdan da anlaşılacağı gibi patternimiz nesne üreten bit metod üzerine kuruludur.Kullanıcı istediği veriyi girer ve işlem gerçekleşir.Gerisi yani nesne oluşumu işlemin gerçekleştirme aşaması istemciyi ilgilendirmez.
Factoy method yapısı genel olarak şu şekildedir.
virtual Product *FactoryMethod(data_type)=0;
Bu tanımlama base (ana) class da yapılır subclass(altsınıf) da bu methedun override edilmesi gerekmektedir.
İşte programımız...
#include
using namespace std;
//**************
//AppStore
//**************
class AppStore
{
protected:
virtual Applications *createApp(string app)=0;
public:
void runApp(string app)
{
Applications *a;
a=createApp(app);
a->run();
}
void stopApp(string app)
{
Applications *a;
a=createApp(app);
a->stop();
}
};
//**************
//MobileAppStore
//**************
class MobileAppStore:public AppStore
{
private:
Applications *createApp(string app)
{
if(app=="twitter")
return new TwitterOnMobile();
else if(app=="skype")
return new SkypeOnMobile();
else if(app=="angry bird")
return new AngryBirdOnMobile();
}
};
/**************
//Applications
//**************
class Applications
{
public:
virtual void run()=0;
virtual void stop()=0;
};
//**************
//SkypeOnMobile
//**************
class SkypeOnMobile:public Applications
{
public:
void run()
{
cout<<"Skype is run on the mobile\n\n";
}
void stop()
{
cout<<"Skype is stopped on the mobile\n\n";
}
};
//**************
//AngryBirdOnMobile
//**************
class AngryBirdOnMobile:public Applications
{
public:
void run()
{
cout<<"AngryBird is run on the mobile\n\n";
}
void stop()
{
cout<<"AngryBird is stopped on the mobile\n\n";
}
};
//****************
//TwitterOnMobile
//****************
class TwitterOnMobile:public Applications
{
public:
void run()
{
cout<<"Twitter is run on the mobile\n\n";
}
void stop()
{
cout<<"Twitter is stopped on the mobile\n\n";
}
};
//**************
//Main
//**************
int main()
{
AppStore *appstore=new MobileAppStore();
appstore->runApp("skype");
appstore->runApp("angry bird");
appstore->stopApp("skype");
appstore->runApp("twitter");
appstore->stopApp("twitter");
appstore->stopApp("angry bird");
system("pause");
return 0;
}
Son olarak bir noktaya daha değinmek istiyorum.Dikkat ederseniz sınıf isimlerimde sürekli mobile kullandım ama istenirse masaüstü uygulamaları da kolayca eklenebilir.
Output...
Hiç yorum yok:
Yorum Gönder