Javascript Factory是一種設(shè)計(jì)模式,它可以被用來(lái)創(chuàng)建對(duì)象。
相比于直接new一個(gè)對(duì)象,使用Javscript Factory可以使代碼更加靈活和可維護(hù)。現(xiàn)在假設(shè)我們需要?jiǎng)?chuàng)建一個(gè)自定義對(duì)象Person,包含屬性name和age,我們可以這樣定義:
function Person(name, age){ this.name = name; this.age = age; }
這樣我們就可以通過(guò)new Person()來(lái)創(chuàng)建一個(gè)Person對(duì)象。但是當(dāng)我們需要?jiǎng)?chuàng)建的屬性較多,或者需要對(duì)屬性進(jìn)行一些預(yù)處理時(shí)使用Factory會(huì)更加方便。
下面是一個(gè)簡(jiǎn)單實(shí)例,我們通過(guò)一個(gè)工廠方法來(lái)創(chuàng)建汽車對(duì)象:
function Car(model, year, miles){ this.model = model; this.year = year; this.miles = miles; this.toString = function(){ return this.model + " has done " + this.miles + " miles"; }; } //工廠方法 function CarFactory(){ this.createCar = function(model, year, miles){ return new Car(model, year, miles); }; } //使用工廠方法創(chuàng)建不同型號(hào)汽車 var carFactory = new CarFactory(); var car1 = carFactory.createCar("Ford Fusion", 2019, 12000); var car2 = carFactory.createCar("Honda Civic", 2018, 8000); console.log(car1.toString()); // Ford Fusion has done 12000 miles console.log(car2.toString()); // Honda Civic has done 8000 miles
在上面的例子中,我們通過(guò)createCar方法來(lái)創(chuàng)建不同型號(hào)的汽車,并且可以通過(guò)toString方法獲取汽車的信息。
Factory還可以通過(guò)傳遞參數(shù)來(lái)進(jìn)行不同類型的創(chuàng)建。例如,我們可以創(chuàng)建一種SUV類型的汽車:
//SUV汽車對(duì)象 function SUV(model, year, miles){ this.model = model; this.year = year; this.miles = miles; this.isSUV = true; this.toString = function(){ return this.model + " is a SUV " + " year "+ this.year + " and has done " + this.miles + " miles"; }; } //SUV工廠方法 function SUVFactory(){ this.createSUV = function(model, year, miles){ return new SUV(model, year, miles); }; } //使用SUV工廠方法來(lái)創(chuàng)建不同型號(hào)的SUV var suvFactory = new SUVFactory(); var suv1 = suvFactory.createSUV("Toyota 4Runner", 2019, 4000); var suv2 = suvFactory.createSUV("Jeep Wrangler", 2017, 6000); console.log(suv1.toString()); // Toyota 4Runner is a SUV year 2019 and has done 4000 miles console.log(suv2.toString()); // Jeep Wrangler is a SUV year 2017 and has done 6000 miles
上述代碼中,我們創(chuàng)建了SUV對(duì)象,并通過(guò)傳遞參數(shù)創(chuàng)建不同型號(hào)的SUV。不同類型的工廠方法使我們能夠創(chuàng)建不同類型的汽車。
總之,使用Factory可以有效幫助我們更加靈活地創(chuàng)建對(duì)象,在維護(hù)代碼時(shí)更加清晰簡(jiǎn)潔。