Home > Java > javaTutorial > body text

java design pattern simple factory pattern

高洛峰
Release: 2016-12-15 14:30:10
Original
1260 people have browsed it

Take purchasing a phone card as an example to illustrate the simple factory pattern

public interface Card {
	
	public void buyTelCard();
	
}
Copy after login
public class MobileCard implements Card {

	@Override
	public void buyTelCard() {
		System.out.println("购买移动卡");
	}

}
Copy after login
public class UnicomCard implements Card {

	@Override
	public void buyTelCard() {
		System.out.println("购买联通卡");
	}

}
Copy after login
public class CardFactory {

	public Card buyCard(String styleName) {
		if (styleName.toLowerCase().equals("mobile")) {
			return new MobileCard();
		} else if (styleName.toLowerCase().equals("unicom")) {
			return new UnicomCard();
		}
		return null;
	}

}/**
 * 
 *  简单工厂模式(Simple Factory Pattern)
 *
 */
public class Test {
	
	public static void main(String[] args) {
		CardFactory factory=new CardFactory();
		factory.buyCard("mobile").buyTelCard();
	}
}
Copy after login


For more articles related to the simple factory pattern of java design patterns, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template