디자인 모델 cocos2d - x 에서 의 사용 - 단순 공장 모델 (Simple Factory)
디자인 모델 의 유형 에 있어 간단 한 공장 모델 은 창설 형 모델 에 속 하고 정적 공장 방법 (Static Factory Method) 모델 이 라 고도 부른다. 하나의 종 류 를 전문 적 으로 정의 함으로써 다른 종류의 실례 를 창설 하 는 것 을 책임 진다. 창 설 된 실례 는 일반적으로 공 통 된 부 류 를 가진다.
간단 한 공장 모델 이 cocos2d - x 에서 어떻게 사용 되 는 지 아래 의 작은 예 를 통 해 알 아 보 겠 습 니 다.
만약 에 우리 가 몬스터 와 유사 한 RPG 게임 을 개발 한다 면 게임 에서 많은 종족 의 캐릭터 가 나타 날 것 이다. 예 를 들 어 인간, 짐승 족 이다.
이 종족 들 은 일반적으로 하나의 종류 로 정의 되 는데, 만약 에 수족 Orc 류, 인종 Human 류 가 있다 면.
짐승 족, 인간 족 두 종 류 는 모두 같은 종족 에 속한다. 그러면 우 리 는 그들 에 게 공 통 된 부 류 를 정의 할 수 있다. 이름 은 종족 Race 류 이다.
종족 이 니 종족 의 이름 이 있 을 것 입 니 다. 어떻게 생 겼 는 지 화면 에 이름과 모습 을 표시 하고 싶 습 니 다. 그러면 우 리 는 아버지 클래스 Race 에서 두 가지 속성, 하나의 이름 name, 하나의 이미지 features 를 정의 합 니 다.
//
// Race.h
// DesignPattern_Factory
//
// Created by cc on 14-6-28.
//
//
#ifndef __DesignPattern_Factory__Race__
#define __DesignPattern_Factory__Race__
using namespace std;
#include "cocos2d.h"
#include "IRaceConst.h"
#include <string>
class Race : public cocos2d::CCSprite {
protected:
//
std::string m_name;
// ( )
std::string m_features;
public:
#pragma mark <getters && setter>
//
// std::string Name() const { return m_name; }
// void Name(std::string val) { m_name = val; }
//
// std::string Features() const { return m_features; }
// void Features(std::string val) { m_features = val; }
#pragma mark < && >
/**
* @brief
*
*/
Race();
/**
* @brief
*
*/
virtual ~Race();
};
#endif /* defined(__DesignPattern_Factory__Race__) */
아버지 류 의 '종족 류' 를 다 쓰 면 우 리 는 인간 족, 짐승 족 과 망령 족 세 가지 종 류 를 실현 할 수 있다.
수족 류:
//
// Orc.h
// DesignPattern_Factory
//
// Created by cc on 14-6-28.
//
//
#ifndef __DesignPattern_Factory__Orc__
#define __DesignPattern_Factory__Orc__
#include "Race.h"
class Orc : public Race {
public:
#pragma mark < && >
/**
* @brief
*
*/
Orc();
/**
* @brief
*
*/
virtual ~Orc();
#pragma mark < && >
/**
* @brief
*
* @return
*/
static Orc* create();
/**
* @brief
*
* @return true: false:
*/
bool init();
};
#endif /* defined(__DesignPattern_Factory__Orc__) */
<pre name="code" class="cpp">//
// Orc.cpp
// DesignPattern_Factory
//
// Created by cc on 14-6-28.
//
//
#include "Orc.h"
#pragma mark < && >
/**
* @brief
*
*/
Orc::~Orc() {
}
/**
* @brief
*
*/
Orc::Orc() {
}
#pragma mark < && >
/**
* @brief
*
* @return
*/
Orc* Orc::create() {
Orc *pRet = new Orc();
if (pRet && pRet->init()) {
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
/**
* @brief
*
* @return true: false:
*/
bool Orc::init(){
this->m_features = "orc.png";
this->m_name = " ";
if (initWithFile(this->m_features.c_str())) {
CCLabelTTF* pLabName = CCLabelTTF::create(this->m_name.c_str(), "Marker Felt", 22.0f);
pLabName->setPosition(ccp(this->getContentSize().width / 2, this->getContentSize().height + 30.0f));
this->addChild(pLabName, 1);
return true;
}
return false;
}
:
// // Human.h // DesignPattern_Factory // // Created by cc on 14-6-28. // // #ifndef __DesignPattern_Factory__Human__ #define __DesignPattern_Factory__Human__ #include "Race.h" USING_NS_CC; class Human : public Race { public: #pragma mark < && > /** * @brief * */ Human(); /** * @brief * */ virtual ~Human(); #pragma mark < && > /** * @brief * * @return */ static Human* create(); /** * @brief * * @return true: false: */ bool init(); }; #endif /* defined(__DesignPattern_Factory__Race__) */
// // Human.cpp // DesignPattern_Factory // // Created by cc on 14-6-28. // // #include "Human.h" #pragma mark < && > /** * @brief * */ Human::~Human() { } /** * @brief * */ Human::Human(){ } #pragma mark < && > /** * @brief * * @return */ Human* Human::create() { Human *pRet = new Human(); if (pRet && pRet->init()) { pRet->autorelease(); return pRet; } CC_SAFE_DELETE(pRet); return NULL; } /** * @brief * * @return true: false: */ bool Human::init(){ this->m_name = " "; this->m_features = "hum.png"; if (initWithFile(this->m_features.c_str())) { CCLabelTTF* pLabName = CCLabelTTF::create(this->m_name.c_str(), "Marker Felt", 22.0f); pLabName->setPosition(ccp(this->getContentSize().width / 2, this->getContentSize().height + 30.0f)); this->addChild(pLabName, 1); return true; } return false; }
자 ~ ~ ~ 짐승 족 과 인간 두 가지 유형 을 다 썼 습 니 다. 우 리 는 짐승 족 과 인간 족 이라는 두 가지 유형 에 각각 자신의 종족 의 이름과 그림 을 나타 내 고 싶 습 니 다. 이 두 가지 유형 이 모두 종족 류 에 속 하 는 이상 우 리 는 Race 류 에서 이 두 가지 사례 를 통일 적 으로 관리 하고 만 들 수 있 습 니 다. 만약 에 우리 가 인간 휴 먼 류 의 대상 을 만 들 려 면 Race 류 에 게 만 알려 주 십시오.저 는 인류 대상 을 만 들 려 고 합 니 다. 이때 Race 류 는 하나의 대상 의 생산 공장 입 니 다. 그의 하위 클래스 라면 모두 그 가 통일 적 으로 만 들 었 습 니 다. 편리 하지 않 습 니까? 다음 코드 를 보 세 요.// // IRaceConst.h // DesignPattern_Factory // // Created by ChengChao on 14-6-28. // // #ifndef __DesignPattern_Factory__IRaceConst__ #define __DesignPattern_Factory__IRaceConst__ /** * @brief */ class IRaceConst { public: // enum RaceType { eRaceTypeNone, eRaceTypeHuman, // eRaceTypeOrc, // eRaceTypeUd, // eRaceTypeNe // }; }; #endif /* defined(__DesignPattern_Factory__IRaceConst__) */
/** * @brief * * @return */ Race* Race::createRaceByType(int aRaceType) { Race* pRace = NULL; switch (aRaceType) { case IRaceConst::eRaceTypeHuman: // pRace = Human::create(); break; case IRaceConst::eRaceTypeOrc: // pRace = Orc::create(); break; case IRaceConst::eRaceTypeUd: // pRace = Ud::create(); break; default: break; } return pRace; }
이 방법 은 Race 류 의 정적 static 공장 방법 입 니 다. 종족 에 들 어 가 는 매 거 진 유형 을 통 해 Race 류 에 의 해 서브 클래스 의 대상 을 통일 시 킵 니 다. 우 리 는 한 종족 을 원 하면 한 종족 유형 을 전달 하고 한 짐승 족 을 원 하면 한 짐승 족 유형 을 전달 합 니 다. 우 리 는 종족 과 짐승 족 을 장면 에 추가 하고 운영 효 과 를 살 펴 보 겠 습 니 다.
Hello WorldScene 중:운행 효 과 는 다음 과 같다.Race* pHumanRace = Race::createRaceByType(IRaceConst::eRaceTypeHuman); pHumanRace->setPosition(ccp(100, 100)); this->addChild(pHumanRace, 1); Race* pOrcRace = Race::createRaceByType(IRaceConst::eRaceTypeOrc); pOrcRace->setPosition(ccp(400, 100)); this->addChild(pOrcRace, 1);
만약 우리 가 지금 또 새로운 수요 가 생 긴 다 면, 망령 족 을 하나 더 넣 었 을 까?한 망령 족 이 종족 을 계승 하 는 Race 를 만 들 고 망령 류 에 하나의 유형 을 지정 하여 종족 상수 의 인 터 페 이 스 를 저장 하 는 IRace Const 에 추가 한 다음 에 정적 공장 방법 Race: create Race ByType () 을 통 해 망령 류 의 인 스 턴 스 를 만 들 고 망령 을 장면 에 추가 하면 됩 니 다. 코드 를 붙 여 보 세 요. 여러분 이 직접 해 보 세 요 ~
마지막 으로 원본 코드 첨부: http://download.csdn.net/detail/oktears/7568355
본 고 는 CC 오리지널 로 정리 하고 전재 할 필요 가 있 으 면 출처 를 밝 혀 주 십시오.http://blog.csdn.net/oktears/article/details/35780455
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
디자인 모델 의 공장 모델, 단일 모델자바 는 23 가지 디자인 모델 (프로 그래 밍 사상/프로 그래 밍 방식) 이 있 습 니 다. 공장 모드 하나의 공장 류 를 만들어 같은 인 터 페 이 스 를 실현 한 일부 종 류 를 인 스 턴 스 로 만 드 는 것...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.