В настоящее время я работаю над игрой, использующей Pattern Component Pattern , и всегда задавался вопросом, как это сделать.У меня есть сущность, которая представляет собой просто набор компонентов.Каждый компонент расширяет класс Component, который просто обладает некоторыми базовыми функциями.
Расширяя класс компонента, создаются новые компоненты для удобного ввода, графики и т. Д. Теперь возникает проблема;Когда я пытаюсь получить конкретный компонент от объекта, он всегда возвращает базовый класс Component, что не позволяет мне использовать определенные функции компонента.
public class GameEntity
{
private ArrayList<Component> components;
public GameEntity()
{
components = new ArrayList<Component>();
}
public void addComponent(Component component)
{
components.add(component);
}
public void update()
{
}
public Component getComponent(Class type)
{
for (Component component : components)
{
if(component.getClass() == type)
{
//return component as Class;
}
}
return null;
}
public void draw(Canvas canvas)
{
for (Component component : components)
{
component.update();
component.draw(canvas);
}
}
}
Некоторые примеры компонентов:
открытый класс GraphicsComponent extends Component {
public Bitmap bitmap;public Rect currentFrameRect;приватный ArrayList spriteAnimations;общедоступная SpriteAnimation currentAnimation;public int x = 0;public int y = 50;public GraphicsComponent () {spriteAnimations = new ArrayList ();}
/**
* Adds image [converts to spriteanimation]
* @param image
*/
public void addImage(Bitmap image, String label)
{
Rect[] tmpRects = {new Rect(0, 0, image.getWidth(), image.getHeight())} ;
addAnimation(new SpriteAnimation(
image, tmpRects, label
));
}
public void addAnimation(SpriteAnimation spriteAnimation)
{
spriteAnimations.add(spriteAnimation);
if(currentAnimation == null)
{
currentAnimation = spriteAnimation;
}
}
@Override
public void update()
{
currentFrameRect = currentAnimation.frames[currentAnimation.currentFrame];
}
@ Переопределить public void draw (Canvas canvas) {
if(currentAnimation != null)
{
currentAnimation.draw(x, y, canvas);
} }
public int getWidth()
{
return currentAnimation.frames[currentAnimation.currentFrame].width();
}
public int getHeight()
{
return currentAnimation.frames[currentAnimation.currentFrame].height();
}
}
public class InteractiveComponent extends Component
{
public GraphicsComponent graphics;
public InteractiveComponent(GraphicsComponent graphics)
{
this.graphics = graphics;
}
public boolean isOver(int tapX, int tapY)
{
//left top right bottom
if(tapX > graphics.x && tapX < graphics.x + graphics.getWidth() &&
tapY > graphics.y && tapY < graphics.y + graphics.getHeight()
)
{
return true;
}
return false;
}
}
Кажется, есть некоторые проблемы с форматированием кода, но это должно бытьЧисто.Я не могу получить доступ к каким-либо конкретным функциям, таким как getHeight () в graphicComponent или isOver () из interactiveComponent, потому что я просто возвращаю базовый компонент.
Я хотел бы вернуть GraphicsComponent или InteractiveComponent на основе класса, который я передаю в getComponent () .