TypeScirpt+CreateJS - Factory Pattern

by Tenderfeel

HTML

<canvas id="demo" width="640" height="480"></canvas>
<script src="https://code.createjs.com/easeljs-0.8.2.min.js"></script>

TypeScript

/// <reference path="https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/createjs/createjs.d.ts" />

//パーティクル作る抽象
abstract class ParticleFactory {
  
  constructor() {
  }
  
	// must be implemented in derived classes
  abstract createOne(): void; 
  
  create (max = 0) {
  	if (max > 0) {
    	return this.createMany(max);
    }
  	return this.createOne();
	}
  
  createMany(max: number) {
  	let result = [];
    
    for (let i = 0; i < max; i++) {
      let particle = this.createOne();
      //particle.x = this.areaWidth * Math.random();
      //particle.y = this.areaHeight * Math.random();
      result[i] = particle;
    }
    
    return result;
  }
}


class CircleParticleFactory extends ParticleFactory {
  createOne() {
    let particle = new createjs.Shape();
    let size = Math.round(Math.random() * 10);
    particle.graphics.beginFill("DeepSkyBlue").drawCircle(0, 0, size);
    return particle; 
  }
}

class StarParticleFactory extends ParticleFactory {
	createOne() {
  	let particle = new createjs.Shape();
    let size = Math.round(Math.random() * 10);
    particle.graphics.beginFill("black");
    // x  y  radius  sides  pointSize  angle 
    particle.graphics.drawPolyStar(0, 0, size, 5, 0.6, -90); 
    return particle; 
  }
}

//パーティクル管理用
class Particles {
	factory: ParticleFactory;
  
	constructor(width: number, height: number) {
  	this.setAreaSize(width, height);
    this.container = new createjs.Container();
  }
  
  setFactory(factory: ParticleFactory) {
  	this.factory = factory;
  }
  
  setAreaSize (width: number, height: number) {
  	this.areaWidth = width;
    this.areaHeight = height;
  }
  
  create (max = 20) {
    let particles = this.factory.create(max);
    for (let particle of particles) {
      particle.x = this.areaWidth * Math.random();
      particle.y = this.areaHeight * Math.random();
      this.container.addChild(particle);
    }
  }
}


let stage = new createjs.Stage("demo");
let circleParticles = new...