What exactly does this phrase mean and in which situations is it used?
It is used as an expression of gloating when someone turns the tables on someone else. There is a good example in the movie Good Will Hunting, where Matt Damon's character (Will Hunting) gets a girl's phone number in a Harvard bar where he, coming from working-class South Boston, is, despite his extraordinary intellect, socio-economically out of his league and is insulted by the Harvard rich kid (Clark) whom he has bested — actually, destroyed — in an argument. On the street later he sees his rival for the girl's attention through a restaurant window. He goes up and raps on the glass to get the young man's attention, and the following dialogue occurs:
It can also be used as an expression of surprise at a sudden turn of fortune.
Robusto's answer does a good job explaining the meaning of the sentence, but for the sake of completeness, here's the origin of the phrase.
Apparently during the first World War, the Allies had an anti-tank grenade which was colloquially referred to as a "toffee apple" thanks to the appearance of its bulb:
In the John Wayne movie "Rio Bravo", one of the characters launches a "toffee apple" at the enemy lines and says the phrase "How you like them apples?" referring, of course, to the bomb. As movie phrases are wont to do, it entered popular consciousness as a boastful expression of triumph.