2. Design Patterns
Characteristc
● Universal solutons of common, repeatng problems
● Descripton of a soluton, not an implementaton
● Mainly depends on OOP paradigm
Pros
● Standardises nomenclature
● Standardises structure
● Independent from programming language
4. Singleton Pattern
● Guarantees creatng only single instance of a class
● Doesn't pollute global namespace
● Overused and treated as new global
● Often used to store configuraton
● Alternatve: Dependency Injecton
6. package foo
{
public class Singleton
{
private static var instance:Singleton;
public function Singleton()
{
}
public static function getInstance():Singleton
{
if (!instance)
{
instance = new Singleton();
}
return instance;
}
}
}
1
2
3
Singleton Pattern
8. Object Pool Pattern
● Creates set of objects ready to use rather then
creatng/removing objects
● Used when creatng new objects is expensive
● You must remember about pool's limit
10. package foo
{
public class EnemyPool
{
private var enemies:Vector.<Enemy>;
public function EnemyPool(count:int)
{
enemies = new Vector.<Enemy>();
while(--count >= 0)
{
enemies.push(new Enemy());
}
}
public function getEnemy():Enemy
{
return enemies.pop();
}
public function returnEnemy(enemy:Enemy):void
{
enemies.push(enemy)
}
}
}
2
3
Object Pool Pattern
1
11. import foo.EnemyPool;
var pool:EnemyPool = new EnemyPool(20);
var enemy:Enemy = pool.getEnemy();
//when we don't need this enemy anymore
pool.returnEnemy(enemy);
2
3
Object Pool Pattern
1
12. Strategy Pattern
● Defines a group of algorithms ready to use
● Allows to change algorithms on runtme
● Helps in proper encapsulaton
14. package foo
{
public class Enemy
{
private var moveStrategy:IMoveStrategy;
public function Enemy(movingStrategy:IMoveStrategy)
{
this.moveStrategy = moveStrategy
}
public function update():void
{
moveStrategy.execute(this);
}
}
}
1
Strategy Pattern
3
2
15. var enemy:Enemy = new Enemy(new FastMoveStrategy());
enemy.move();
1
Strategy Pattern
16. Command Pattern
● Encapsulates all data needed to method invocaton later on
● Single Responsibility Principle
● Fire and Forget
● Commonly used for mult-level undo
18. package foo
{
public class CreateEnemyCommand implements ICommand
{
public function execute():void
{
//add enemy & play sound here
}
}
}
1
Command Pattern
22. Task 1
Game model:
● Create GameModel singleton class responsible for
storing game data:
● Enemies and bullets
● Game object reference
● Giant object reference
enemies bullets game
lives
giant
23. Task 2
Bullet Pool:
● Create pool of 50 bullets using Object Pool Pattern
BulletPool
24. Task 3
Enemies' movement:
● Create strategies FastMoveStrategy and SineWaveMoveStrategy
responsible for moving enemies
enemy_1 enemy_2