Java Tutorial/Design Pattern/Factory Pattern
Версия от 17:44, 31 мая 2010; (обсуждение)
A simple static factory method.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
abstract class Shape {
public abstract void draw();
public abstract void erase();
public static Shape factory(String type) {
if (type.equals("Circle"))
return new Circle();
if (type.equals("Square"))
return new Square();
throw new RuntimeException("Bad shape creation: " + type);
}
}
class Circle extends Shape {
Circle() {
} // Package-access constructor
public void draw() {
System.out.println("Circle.draw");
}
public void erase() {
System.out.println("Circle.erase");
}
}
class Square extends Shape {
Square() {
} // Package-access constructor
public void draw() {
System.out.println("Square.draw");
}
public void erase() {
System.out.println("Square.erase");
}
}
public class ShapeFactory {
public static void main(String args[]) {
List<Shape> shapes = new ArrayList<Shape>();
Iterator it = Arrays.asList(
new String[] { "Circle", "Square", "Square", "Circle", "Circle", "Square" }).iterator();
while (it.hasNext())
shapes.add(Shape.factory((String) it.next()));
it = shapes.iterator();
while (it.hasNext()) {
Shape s = (Shape) it.next();
s.draw();
s.erase();
}
}
}
Creating and Extending Objects with the Factory Patterns
public class MainClass {
public static void main(String args[]) {
SecureFactory factory;
factory = new SecureFactory();
Connection connection = factory.createConnection("Oracle");
System.out.println("You"re connecting with " + connection.description());
}
}
class SecureFactory extends ConnectionFactory {
public Connection createConnection(String type) {
if (type.equals("Oracle")) {
return new SecureOracleConnection();
} else if (type.equals("SQL Server")) {
return new SecureSqlServerConnection();
} else {
return new SecureMySqlConnection();
}
}
}
abstract class Connection {
public Connection() {
}
public String description() {
return "Generic";
}
}
abstract class ConnectionFactory {
public ConnectionFactory() {
}
protected abstract Connection createConnection(String type);
}
class SqlServerConnection extends Connection {
public SqlServerConnection() {
}
public String description() {
return "SQL Server";
}
}
class SecureSqlServerConnection extends Connection {
public SecureSqlServerConnection() {
}
public String description() {
return "SQL Server secure";
}
}
class SecureOracleConnection extends Connection {
public SecureOracleConnection() {
}
public String description() {
return "Oracle secure";
}
}
class SecureMySqlConnection extends Connection {
public SecureMySqlConnection() {
}
public String description() {
return "MySQL secure";
}
}