Now, imagine that the company you work for wants a blog with different types of articles— text-based articles and image-based articles. What they want is simple: a text-based article that is made of a String, and an image-based article that stores the URL of the image. All types of articles need to have a title.
At first, let's write the Article
class. This one will define what all articles have.
class Article { public var title : String; }
Notice that we did not create a constructor for this class: an article has to be either text-based or image-based in this example, being able to construct an instance of the Article
class would be nonsense.
We want text-based and image-based articles to be able to generate some HTML code, but each one will need to do it in its own way. To make it usable by a calling function, we will define an IHTMLGenerator
interface, as follows:
interface IHTMLGenerator { public function generateHTML() : String; }
class TextArticle extends Article, implements IHTMLGenerator { public var text : String; public function new(text : String) { this.text = text; } public function generateHTML() : String { returnStringTools.htmlEscape(text); } }
class ImageArticle extends Article, implements IHTMLGenerator { public var imageUrl : String; public function new(url : String) { this.imageUrl = url; } public function generateHTML() : String { return '<imgsrc="' + this.imageUrl + '" alt=' + this.title + '/>'; } }
Main
class, we will add two methods: one that displays the title of an article and one that outputs its HTML code:class Main { public static function main() { var imgArt : ImageArticle; imgArt = new ImageArticle ("http://www.someuninterestingblog.unexistingtld/someimage.png"); imgArt.title = "Some unexisting image"; var textArt : TextArticle; textArt = new TextArticle("This is an interesting text"); textArt.title = "Some interesting article"; displayArticleTitle(imgArt); outputHTMLCode(imgArt); displayArticleTitle(textArt); outputHTMLCode(textArt); } public static function displayArticleTitle(art : Article) { trace(art.title); } public static function outputHTMLCode (generator : IHTMLGenerator) { trace(generator.generateHTML()); } }
Main.hx:20: Some unexisting image Main.hx:25: <img src="http://www.someuninterestingblog.unexistingtld/someimage.png"/> Main.hx:20: Some uninteresting article Main.hx:25: This is an uninteresting text
3.145.166.149