There is a major class Panorama
with parts as composition PanoramaViewOver
.
class Panorama {
panoramaViewOver: PanoramaViewOver | null;
}
Who is responsible to create a class PanoramaViewOver
if needed?
I can create wrapper class that creates a new Panorama()
and creates a PanoramaViewOver()
:
class Creator {
panorama: Panorama;
createPanorama() {
this.panorama = new Panorama();
}
createPanoramaViewOver() {
const view = new PanoramaViewOver();
if(this.panorama) this.panorama.view = view;
}
}
Another way is create a public method createPanoramaViewOver()
inside main class Panorama()
.
What is a better way?
CodePudding user response:
Instead of createPanorama()
and createPanoramaViewOver()
I would use create()
which implicitly creates a Panorama
instance and createWithPanorama(Panorama panorama)
which takes an already initialized Panorama
object.
Both methods would need to be static resembling a factory method pattern.
This way you can set panorama.view
outside of the Creator
class.
It would look like this:
class Creator {
private _panorama: Panorama | null;
constructor(panorama : Panorama | null) {
this._panorama = panorama;
}
static create() {
return new Creator(new Panorama());
}
static createWithPanorama(panorama : Panorama | null) {
return new Creator(panorama);
}
}
You would use it like this:
let creator = Creator.create();
let creatorWithoutPanorama = Creator.createWithPanorama(null);
let p = new Panorama();
p.view = /* something */;
let creatorWithPanoramaViewOver = Creator.createWithPanorama(p);
It's not idiomatic to initialize each member of a class with different methods.
You usually do that in one place only, most of the time in the constructor.