2014-02-13 170 views
1

這是什麼我已經做Grails中一個非常簡單的例子:我在尋找這樣做的更多的面向對象的方式,像依賴注入:條件

// this can be a service or normal class 
public abstract class Person { 
    public final String introduceSelf() { 
     return "Hi, I'm " + getFullName() 
    } 

    protected abstract String getFullName() 
} 

// Service 
class AlexService extends Person { 
    protected String getFullName() { 
     return "Alex Goodman" 
    } 
} 

// Service 
class BobService extends Person { 
    protected String getFullName() { 
     return "Bob Goodman" 
    } 
} 

// Service 
class CarlService extends Person { 
    protected String getFullName() { 
     return "Carl Goodman" 
    } 
} 

// Controller 
class IntroduceController { 
    def alex 
    def bob 
    def carl 

    def index() { 
     if(params.person == "a") 
      render alex.introduceSelf() 
     if(params.person == "b") 
      render bob.introduceSelf() 
     if(params.person == "c") 
      render carl.introduceSelf() 
    } 
} 

// Controller 
class IntroduceController { 
    def person 

    def index() { 
     // inject a proper person in a more object oriented way 

     render person.introduceSelf() 
    } 
} 

你能否建議如何以更加面向對象/動態的方式實現這一點?

回答

0
class IntroduceController { 

    def grailsApplication 

    def index() { 
    def person = grailsApplication.mainContext.getBean(params.person) 
    person.doSomething() 
    } 

} 

您必須確保,你的服務的名稱對應params.person值,params.person = 'bob'會工作,params.person = 'b'不會

+0

對於簡單地持有一個類而言,bean是一個好主意,它會高效嗎? – user809790