Factory Method

来源:互联网 发布:网络优化软件哪个好 编辑:程序博客网 时间:2024/06/06 08:30

Intent: Define an interface for creating an object,but let subclasses decide which class to instantiate. Factory Methodlets a class defer instantiation to subclasses.

Structure

Factory Method in UML

Participants:

  • Product: defines the interface of objects the factory method creates.
  • ConcreteProduct: implements the Product interface.
  • Creator:declares the factory method, which returns an object of type Product.Creator may also define a default implementation of the factory methodthat returns a default ConcreteProduct object.
  • ConcreteCreator: overrides the factory method to return an instance of a ConcreteProduct.

Collaborations:Creator relies on its subclasses to define the factory method so thatit returns an instance of the appropriate ConcreteProduct.

 

When to Use a Factory Pattern
You should consider using a Factory pattern when
· A class can’t anticipate which kind of class of objects it must create.
· A class uses its subclasses to specify which objects it creates.
· You want to localize the knowledge of which class gets created.
There are several similar variations on the factory pattern to
recognize.
1. The base class is abstract and the pattern must return a complete working
class.
2. The base class contains default methods and is only subclassed for cases
where the default methods are insufficient.
3. Parameters are passed to the factory telling it which of several class types
to return. In this case the classes may share the same method names but
may do something quite different.

 

Simple Code Example:

class NameFactory {
//returns an instance of LastFirst or FirstFirst
//depending on whether a comma is found
public Namer getNamer(String entry) {
int i = entry.indexOf(","); //comma determines name
order
if (i>0)
return new LastFirst(entry); //return one class
else
return new FirstFirst(entry); //or the other
}
}

 

class Namer {
//a simple class to take a string apart into two names
protected String last; //store last name here
protected String first; //store first name here
public String getFirst() {
return first; //return first name
}
public String getLast() {
return last; //return last name
}
}

 

class FirstFirst extends Namer { //split first last
public FirstFirst(String s) {
int i = s.lastIndexOf(" "); //find sep space
if (i > 0) {
//left is first name
first = s.substring(0, i).trim();
//right is last name
last =s.substring(i+1).trim();
}
else {
first = “”; // put all in last name
last = s; // if no space
}
}
}

 

class LastFirst extends Namer { //split last, first
public LastFirst(String s) {
int i = s.indexOf(","); //find comma
if (i > 0) {
//left is last name
last = s.substring(0, i).trim();
//right is first name
first = s.substring(i + 1).trim();
}
else {
last = s; // put all in last name
first = ""; // if no comma
}
}
}

原创粉丝点击