Using the same function for different class instances
I have a piece of code, that moves an array depending on it's type. If the array is of TypeA objects, it will change TypeA. If it is TypeB it will change TypeB. The issue with the current code is the repeative blocks.
private function scrollRight():void
{
if (SELECTED == CONSTANT)
{
if (_avatarDataInstance.isFirstPage())
{
_buttons.enableLeftScroll();
}
setCurrentItems(_avatarDataInstance.getNextPage());
if (_avatarDataInstance.isLastPage())
{
_buttons.disableRightScroll();
}
}
if (SELECTED == DECOR)
{
开发者_开发知识库if (_decorDataInstance.isFirstPage()) {
_buttons.enableLeftScroll();
}
setCurrentItems(_decorDataInstance.getNextPage());
if (_decorDataInstance.isLastPage()) {
_buttons.disableRightScroll();
}
}
}
This would be my idea code, where _selectedInstance is the instance of either TypeA or TypeB whichever is selected (TypeA and TypeB are classes).
private function scrollRight():void
{
if (_selectedInstance.isFirstPage())
{
_buttons.enableLeftScroll();
}
setCurrentItems(_selectedInstance.getNextPage());
if (_selectedInstance.isLastPage())
{
_buttons.disableRightScroll();
}
Any way, I can achieve this in actionscript? I have tried this :
_selectedInstance:Class;
if(somethingA)
selectedInstance(somethingA);
else
selectedInstance(somethingB);
Which stops working whenever I need to access any property (user) selectedInstance.testSomething();
You could create an interface or an abstract class , let's say TypeAbstract for instance , that TypeA and TypeB would extend ( or implement , depending on your choice ).
private function scrollRight():void { var instance:TypeAbstract; switch( SELECTED ) { case CONSTANT: instance = _avatarDataInstance as TypeA; break; case DECOR: instance = _decorDataInstance as TypeB; break; } if(instance.isFirstPage() ) _buttons.enableLeftScroll(); setCurrentItems(instance.getNextPage()); if(instance.isLastPage() ) _buttons.disableRightScroll(); }
The general idea is to implement the common methods for TypeA & TypeB in the TypeAbstract class. Then you can override these methods in TypeA & TypeB to adapt the methods to the specifics of the subclass. For more detailed information, check the links given by George Profenza.
精彩评论