Design excerpt from a long time college
Read the article on the Forum, reading FactoryMethod pattern UML diagram, wrote a small example program. As a supplement to the article!
Creator.java
Public abstract class Creator
{
/**
* Looks like a factory
* contains some products and some process methods
*/
protected Product duct;
Abstract String processproduct ();
Abstract String processproductspecial ();
Public String Operation ()
{
return processproduct (); FactoryMethod for Implemention;
}
}
Concreteproduct.java
public class Concreteproduct extends Product
{
Public Concreteproduct ()
{
System.out.println ("Construct the Concreteproduct object");
}
public string makestring (String str)
{
Return ' This is the ' product after processing: ' +str;
}
}
Product.java
Public abstract class Product
{
Public abstract string makestring (String str);
}
Concretecreatora.java
public class Concretecreatora extends Creator
{
/**
* You can write some the other class like this to override
* The same methods do diffrent thing;
*/
Public Concretecreatora ()
{
Duct=new concreteproduct ();
System.out.println ("instanced a Product");
}
Public String processproduct ()
{
SYSTEM.OUT.PRINTLN ("Product A:");
Return duct.makestring (' Make @ #a product ');
}
Public String processproductspecial ()
{
SYSTEM.OUT.PRINTLN ("Special product B:");
Add another method here
Return duct.makestring (' Make Special @ #B product ');
}
}
Testfactorymethod.java
public class Testfactorymethod
{
Public Testfactorymethod ()
{
}
public static void Main (string[] arg)
{
Concretecreatora cc=new Concretecreatora ();
System.out.println (CC. Operation ());
System.out.println (Cc.processproductspecial ());
}
}
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.